FastAPI is a modern, fast (high-performance) Python web framework for building APIs. One of its standout features is its intuitive and powerful request handling system. In this blog post, we'll explore how FastAPI handles requests and how to leverage path parameters to create dynamic API endpoints.
When a client sends a request to your FastAPI application, the framework takes care of parsing the incoming data and routing it to the appropriate endpoint. This process involves several steps:
FastAPI handles all of these steps automatically, making it easy for developers to focus on building their application logic.
Path parameters are variables extracted from the URL path. They allow you to create dynamic routes that can handle different inputs. Let's look at a simple example:
from fastapi import FastAPI app = FastAPI() @app.get("/users/{user_id}") async def read_user(user_id: int): return {"user_id": user_id}
In this example, {user_id}
is a path parameter. When a request is made to /users/123
, FastAPI automatically extracts the value 123
and passes it to the read_user
function as the user_id
parameter.
One of the great features of FastAPI is automatic type conversion and validation. In the previous example, we declared user_id
as an int
. FastAPI will automatically convert the string from the URL to an integer and validate it. If a non-integer value is provided, FastAPI will return a detailed error response.
You can use multiple path parameters in a single route. Here's an example:
@app.get("/users/{user_id}/posts/{post_id}") async def get_user_post(user_id: int, post_id: int): return {"user_id": user_id, "post_id": post_id}
This route will match URLs like /users/42/posts/7
, extracting both user_id
and post_id
.
While path parameters are typically required, you can make them optional by using Pydantic's Optional
type:
from typing import Optional from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: Optional[int] = None): if item_id is None: return {"message": "No item ID provided"} return {"item_id": item_id}
This route will work for both /items/42
and /items/
.
You can use Python's Enum
class to create path parameters with predefined values:
from enum import Enum from fastapi import FastAPI class ModelName(str, Enum): alexnet = "alexnet" resnet = "resnet" lenet = "lenet" app = FastAPI() @app.get("/models/{model_name}") async def get_model(model_name: ModelName): if model_name == ModelName.alexnet: return {"model_name": model_name, "message": "Deep Learning FTW!"} if model_name.value == "lenet": return {"model_name": model_name, "message": "LeCNN all the images"} return {"model_name": model_name, "message": "Have some residuals"}
This ensures that only predefined values are accepted for the model_name
parameter.
FastAPI allows you to use both path parameters and query parameters in the same route:
from fastapi import FastAPI app = FastAPI() @app.get("/users/{user_id}/items") async def read_user_items(user_id: int, skip: int = 0, limit: int = 10): return {"user_id": user_id, "skip": skip, "limit": limit}
In this example, user_id
is a path parameter, while skip
and limit
are query parameters. This route would match a URL like /users/42/items?skip=20&limit=50
.
Path parameters are a powerful feature in FastAPI that allow you to create flexible and dynamic API endpoints. By understanding how to effectively use path parameters, you can build more robust and user-friendly APIs. Remember to leverage FastAPI's automatic type conversion and validation to ensure your API handles input correctly and provides meaningful error messages when necessary.
15/11/2024 | Python
26/10/2024 | Python
21/09/2024 | Python
08/12/2024 | Python
05/10/2024 | Python
17/11/2024 | Python
15/11/2024 | Python
05/11/2024 | Python
15/11/2024 | Python
17/11/2024 | Python
26/10/2024 | Python
26/10/2024 | Python