There are many projects in Python that we can use to create an API. After exploring a few options, I decided to go with FastAPI and explore it over the next few weeks. FastAPI is not only fast when it comes to serving requests, but also when it comes to writing code for it. Let us explore the many features we can use while we create our API.
This post is part of my journey to learn Python. You find the code for this post in my PythonFriday repository on GitHub.
Installation
The main speed advantage of FastAPI comes from the asynchronous processing of requests. Therefore, we not only need to install FastAPI itself, but we also need to install an ASGI server to use its asynchronous features:
1 2 |
pip install fastapi pip install "uvicorn[standard]" |
A minimalistic API
For our first steps we can use the minimalistic example from the FastAPI documentation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} |
The code reminds me a lot of Flask, except for the async keyword and the type hints. While we do not need the async keyword for those specific methods, I like to have them consistent with the rest of the application. As we add more functionality over the next weeks, we will see where we can benefit from asynchronous processing.
Run the API
We can run our API inside uvicorn with this command:
1 |
uvicorn main:app --reload |
INFO: Will watch for changes in these directories: [‘C:\\FastAPI\\quickstart’]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [48200] using WatchFiles
INFO: Started server process [62140]
INFO: Waiting for application startup.
INFO: Application startup complete.
Our application (the app
variable in the main.py
file) is now running on port 8000
and will reload if we change a file. When we open the URL in the browser, we should see this output:
Explore the documentation
If we open the URL http://127.0.0.1:8000/docs we see one of the magical parts of FastAPI in action. Without any code written by us we get the Swagger documentation for all our endpoints:
We can explore our API through the web browser and download the OpenAPI secification for our API – all without extra work from us.
Next
With our minimalistic API we already have a lot in place: There are our specified endpoints, an asynchronous-capable server and the OpenAPI specification that documents our API. Next week we explore the async keyword that we put in front of the method definitions.
5 thoughts on “Python Friday #214: First Steps With FastAPI”