Fast API Built In Features
Fast API Built In Features
A look at the key components that make FastAPI so powerful.
Core Framework (Starlette)
This forms the fundamental structure of your application.
- Applications, Routing, Endpoints, Middleware, Responses, WebSockets, Exceptions: All of these are core functionalities inherited from Starlette.
Use Cases:
- Routing: Define how your application responds to different URL paths (`@app.get("/items/{item_id}")`).
- Middleware: Perform actions on every request and response, such as adding custom headers, handling CORS, or logging request details.
- WebSockets: Build real-time applications like a live chat or a stock ticker that pushes data to the client as it becomes available.
- Exceptions: Customize how your API handles errors, returning clean, consistent JSON responses instead of default server errors.
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}
Data Handling (Pydantic)
FastAPI's tight integration with Pydantic makes data validation and serialization effortless.
- API Schemas: You declare the shape of your data using Python type hints and Pydantic models.
Use Cases:
- Request Body Validation: Automatically validate a JSON payload on a POST request, ensuring all required fields are present and correctly typed (e.g., `name: str`, `price: float`). If the data is invalid, the user receives a detailed error message.
- Response Serialization: Define a response model to ensure your API always returns data in a consistent format, filtering out any unwanted fields.
- Automatic Docs: The Pydantic models are used to automatically generate the full OpenAPI schema, which powers the interactive documentation pages at `/docs` and `/redoc`.
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool | None = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
Dependency Injection System
Description:
The Dependency Injection system lets you declare "dependencies" (functions or classes) that your endpoint functions need to run. FastAPI takes care of calling these dependencies and "injecting" their return values as arguments into your endpoint function.
Use Cases:
- Authentication: Inject a function that validates an API key or an OAuth2 token. If the token is invalid, the dependency can raise an HTTP exception, and the endpoint function will never be called.
- Database Connections: Inject a database session into an endpoint. The dependency can manage opening the connection before the request and closing it afterward, ensuring resource cleanup is handled automatically.
- Shared Logic: Reuse code for tasks like pagination. You can define a dependency that returns `(skip, limit)` from query parameters and reuse it across multiple endpoints.
from fastapi import FastAPI, Depends
app = FastAPI()
async def get_current_user():
# Placeholder for actual authentication logic
return {"username": "fastapi_user"}
@app.get("/users/me")
async def read_current_user(current_user: dict = Depends(get_current_user)):
return current_user
Background Tasks
Description:
The `BackgroundTasks` class is a built-in feature for running functions in the background after your endpoint has returned a response to the client.
Use Cases:
- Sending Emails: When a user registers, your API can send an immediate "200 OK" response while a background task handles sending the welcome email.
- Processing Data: For an image upload endpoint, you can return a response right away while a background task resizes and processes the image.
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(message: str):
with open("log.txt", "a") as log_file:
log_file.write(message)
@app.post("/send-log/")
async def send_log(background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, "Log entry added!\n")
return {"message": "Log entry accepted, processing in background."}
Testing Tools
FastAPI provides a simple and effective way to test your application.
- Test Client: The `TestClient` from `fastapi.testclient` is a class that allows you to make synchronous requests to your asynchronous FastAPI application for testing purposes.
Use Cases:
- Integration Tests: You can write tests that send `GET`, `POST`, `PUT`, and `DELETE` requests to your endpoints and assert on the status codes, response content, and headers. The tests run against your application in memory, making them very fast.
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_read_hello():
response = client.get("/hello/world")
assert response.status_code == 200
assert response.json() == {"message": "Hello world"}
Other Built-in Features
These are additional features that come out-of-the-box.
- Static Files: FastAPI can serve static files, such as CSS, JavaScript, and images, directly from your application.
- Server Push: A feature from Starlette that allows the server to proactively send resources to the browser before the client even requests them, improving performance.
Use Cases:
- Static Files Use Case: You can use this to serve the files for your frontend UI if your application is serving both the API and a web interface.
- Server Push Use Case: For a simple web app, you can "push" the required CSS and JS files along with the initial HTML page, reducing the number of requests the browser has to make.
Comments
Post a Comment