Understanding FastAPI basics
As we embark on our journey with FastAPI, it’s essential to build a solid foundation. FastAPI isn’t just another web framework; it’s a powerful tool designed to make your life as a developer easier, your applications faster, and your code more robust and maintainable.
In this recipe, we’ll demystify the core concepts of FastAPI, delve into its unique features such as asynchronous programming, and guide you through creating and organizing your first endpoints. By the end of the recipe, you’ll have your first FastAPI server up and running – a milestone that marks the beginning of an exciting journey in modern web development.
FastAPI is a modern, fast web framework for building APIs with Python based on standard Python type hints.
Key features that define FastAPI are the following:
- Speed: It’s one of the fastest frameworks for building APIs in Python, thanks to its underlying Starlette framework for web parts and Pydantic for data handling
- Ease of use: FastAPI is designed to be easy to use, with intuitive coding that accelerates your development time
- Automatic documentation: With FastAPI, the API documentation is generated automatically, a feature that is both a time-saver and a boon for developers
How to do it…
We will now explore how to use those features effectively with some general guidance.
We will go through the following steps:
- Applying asynchronous programming to our existing endpoints to improve time efficiency
- Exploring routers and endpoints to better organize large code bases
- Running your first FastAPI server with a basic configuration
- Exploring the automatic documentation
Applying asynchronous programming
One of the most powerful features of FastAPI is its support for asynchronous programming. This allows your applications to handle more requests simultaneously, making them more efficient. Asynchronous programming is a style of concurrent programming in which tasks are executed without blocking the execution of other tasks, improving the overall performance of your application. To integrate asynchronous programming smoothly, FastAPI leverages the async
/await
syntax (https://fastapi.tiangolo.com/async/) and automatically integrates asynchronous functions.
So, the read_root()
function in main.py
from the previous code snippet in the Creating a new FastAPI project recipe can be written as follows:
@app.get("/") async def read_root(): return {"Hello": "World"}
In this case, the behavior of the code will be exactly the same as before.
Exploring routers and endpoints
In FastAPI, organizing your code into routers and endpoints is a fundamental practice. This organization helps in making your code cleaner and more modular.
Endpoints
Endpoints are the points at which API interactions happen. In FastAPI, an endpoint is created by decorating a function with an HTTP method, such as @app.get("/")
.
This signifies a GET
request to the root of your application.
Consider the following code snippet:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"}
In this snippet, we define an endpoint for the root URL ("/"
). When a GET
request is made to this URL, the read_root
function is invoked, returning a JSON response.
Routers
When we need to handle multiple endpoints that are in different files, we can benefit from using routers. Routers assist us in grouping our endpoints into different modules, which makes our code base easier to maintain and understand. For example, we could use one router for operations related to users and another for operations related to products.
To define a router, first create a new file in the fastapi_start
folder called router_example.py
. Then, create the router as follows:
from fastapi import APIRouter router = APIRouter() @router.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
You can now reuse it and attach the router to the FastAPI server instance in main.py
:
import router_example from fastapi import FastAPI app = FastAPI() app.include_router(router_example.router) @app.get("/") async def read_root(): return {"Hello": "World"}
You now have the code to run the server that includes the router for the GET /items
endpoint importer from another module.
Running your first FastAPI server
To run your FastAPI application, you need to point Uvicorn to your app instance. If your file is named main.py
and your FastAPI instance is called app
, you can start your server like this at the fastapi_start
folder level:
$ uvicorn main:app --reload
The --reload
flag makes the server restart after code changes, making it ideal for development.
Once the server is running, you can access your API at http://127.0.0.1:8000
. If you visit this URL in your browser, you’ll see the JSON response from the "/"
endpoint we have just created.
Exploring the automatic documentation
One of the most exciting features of FastAPI is its automatic documentation. When you run your FastAPI application, two documentation interfaces are automatically generated: Swagger UI and Redoc.
You can access these at http://127.0.0.1:8000/docs
for Swagger UI and http://127.0.0.1:8000/redoc
for Redoc.
These interfaces provide an interactive way to explore your API and test its functionality.
See also
You can discover more about what we covered in the recipe at the following links:
- First Steps: https://fastapi.tiangolo.com/tutorial/first-steps/
- Docs URLs: https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls
- Concurrency and async / await: https://fastapi.tiangolo.com/async/