How to Create Routes with FastAPI
FastAPI is a modern and efficient Python framework for building APIs. With FastAPI, you can easily define and handle routes to create robust and scalable web applications or microservices. In this article, we will guide you through the process of creating routes with FastAPI.
Understanding Routes in FastAPI
Routes play a crucial role in FastAPI applications as they define the endpoints that clients can interact with. Each route is associated with a specific URL and HTTP method, allowing you to handle different types of requests, such as GET, POST, PUT, DELETE, and more. By creating routes, you can build the API endpoints that enable communication between your application and clients.
Creating Routes in FastAPI
To create routes in FastAPI, follow these steps:
Step 1: Import Dependencies
Start by importing the necessary dependencies in your Python file:
from fastapi import FastAPI
Step 2: Create a FastAPI App
Next, create an instance of the FastAPI application:
app = FastAPI()
Step 3: Define Routes
Use decorators provided by FastAPI to define routes. Decorators enable you to associate functions with specific URLs and HTTP methods.
Here’s an example of a basic route that handles the root URL and responds with a simple message:
@app.get("/")
def root():
return {"message": "Hello, World!"}
In this case, @app.get("/")
indicates that the root()
function will handle GET requests to the root URL ("/").
Step 4: Handle Path Parameters
FastAPI allows you to handle path parameters in your routes. Path parameters are portions of the URL that can vary and are enclosed in curly braces {}
.
@app.get("/users/{user_id}")
def get_user(user_id: int):
# Logic to retrieve user data
return {"user_id": user_id, "name": "John Doe"}
In this example, the user_id
is a path parameter that will be passed as an argument to the get_user()
function.
Step 5: Handle Query Parameters
Query parameters are used to provide additional information in the URL. FastAPI supports handling query parameters using function arguments with default values.
@app.get("/items/")
def get_items(skip: int = 0, limit: int = 10):
# Logic to retrieve items from the database
return {"skip": skip, "limit": limit}
In this case, the skip
and limit
parameters are query parameters that can be provided in the URL like this: /items/?skip=10&limit=5
.
Step 6: Handle Request Body
When dealing with requests that include a JSON body, you can define the expected structure using Pydantic models.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items")
def create_item(item: Item):
# Logic to create and save the item
return item
In this example, the create_item()
route expects a JSON object in the request body that matches the structure defined in the Item
model.
Step 7: Run the App
Finally, you need to run your FastAPI application using an ASGI server. Uvicorn is a commonly used option:
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8200)
Conclusion
Creating routes with FastAPI is a straightforward and convenient process. By defining routes and associating them with specific URLs and HTTP methods, you can build powerful APIs to handle various types of requests. In this article, we covered the essential steps for creating routes with FastAPI. Now you can start building robust and efficient web applications or microservices using FastAPI’s intuitive routing system.