Python > Web Development with Python > Asynchronous Web Frameworks (e.g., FastAPI, AsyncIO) > Routing in FastAPI
Basic Routing in FastAPI
This snippet demonstrates the fundamental concept of routing in FastAPI, showing how to define different endpoints and associate them with specific functions (or 'path operation functions'). It illustrates how FastAPI uses decorators to map HTTP methods (like GET, POST) and URL paths to Python functions.
Code Example
This code defines a FastAPI application with three routes: The The
/
: A GET request to the root path returns a simple JSON response./items/{item_id}
: A GET request to this path, where item_id
is a path parameter (an integer), returns the item ID along with an optional query parameter q
./items/
: A POST request to this path allows creating a new item, taking name
(required) and an optional description
as input.@app.get()
and @app.post()
decorators are the core of routing in FastAPI. They tell FastAPI which function should be executed when a request matching the specified method and path is received.async
keyword indicates that these functions are asynchronous, allowing FastAPI to handle concurrent requests efficiently.
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: str = None):
return {"item_id": item_id, "q": q}
@app.post("/items/")
async def create_item(name: str, description: str = None):
return {"name": name, "description": description}
Concepts Behind the Snippet
Path Parameters: FastAPI allows you to define parameters within the URL path using curly braces ( Query Parameters: You can also define query parameters in your routes. These are parameters that appear after the question mark ( HTTP Methods: FastAPI supports all standard HTTP methods, including GET, POST, PUT, DELETE, etc. Each method corresponds to a different operation you might perform on a resource. Asynchronous Operations: Using {}
). These parameters are passed as arguments to the path operation function. In the example, item_id
is a path parameter.?
) in the URL (e.g., /items/123?q=search_term
). FastAPI automatically handles parsing and validating these parameters.async
ensures that your web application can handle multiple requests concurrently without blocking. This is crucial for building scalable web applications.
Real-Life Use Case
Imagine building an e-commerce API. You might use routes like: Each of these routes would be associated with a function that handles the corresponding logic (e.g., querying the database, creating a new record, etc.).
/products
(GET) to list all products./products/{product_id}
(GET) to retrieve a specific product./products
(POST) to create a new product./orders/{order_id}
(GET) to retrieve an order.
Best Practices
Keep routes organized: Use meaningful and consistent naming conventions for your routes. Use path parameters wisely: Use them for identifying specific resources. Avoid using them for filtering or searching. Leverage FastAPI's validation: FastAPI automatically validates path and query parameters based on their type hints (e.g., Use async/await: Always use item_id: int
). This helps prevent errors and improve the robustness of your application.async
and await
for I/O-bound operations (e.g., database queries, network requests) to avoid blocking the event loop.
Interview Tip
Be prepared to explain the difference between path parameters and query parameters. Understand how FastAPI uses type hints for validation and how asynchronous programming contributes to application performance. Also understand RESTful API design principles in conjunction with FastAPI routing.
When to Use Them
Use routing to define the entry points to your application. Each route should correspond to a specific action or resource. Routing is the core mechanism for building a RESTful API or any web application where different URLs map to different functionalities.
Alternatives
Alternatives to FastAPI's routing mechanism include those offered by other web frameworks like Flask (using @app.route
) and Django (using URL patterns defined in urls.py
). However, FastAPI offers built-in validation, automatic documentation, and asynchronous support, often making it a more modern and efficient choice.
Pros
Simplicity: Easy to define routes using decorators. Automatic Validation: Type hints enable automatic data validation and conversion. Asynchronous Support: Built-in support for asynchronous programming. Automatic Documentation: Generates OpenAPI documentation based on your routes.
Cons
Learning Curve: Requires understanding of asynchronous programming concepts (async/await). Framework Dependency: Tightly coupled to the FastAPI framework.
FAQ
-
What happens if I try to access a route that doesn't exist?
FastAPI will return an HTTP 404 Not Found error. -
Can I use regular expressions in my routes?
Yes, you can use regular expressions to define more complex route patterns. Refer to the FastAPI documentation for details on how to do this. -
How do I handle different HTTP methods for the same route?
You can define multiple functions for the same route, each decorated with a different HTTP method decorator (e.g.,@app.get()
,@app.post()
).