FastAPI is a modern, fast (high-performance) Python web framework for building APIs. It's designed to be easy to use, fast to code, and ready for production. FastAPI is based on Starlette for the web parts and Pydantic for the data parts, making it a powerful tool for building RESTful APIs.
Let's dive into the key features and concepts of FastAPI:
First, install FastAPI and its dependencies:
pip install fastapi[all]
Now, let's create a simple "Hello, World!" API:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello, World!"}
To run the server:
uvicorn main:app --reload
Visit http://localhost:8000
in your browser, and you'll see the JSON response.
FastAPI makes it easy to handle different HTTP methods and path parameters:
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
In this example, item_id
is a path parameter that FastAPI will automatically convert to an integer.
You can easily define query parameters:
from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit}
Now, you can call /items/?skip=20&limit=30
to customize the query.
FastAPI uses Pydantic models to define request bodies:
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str = None price: float tax: float = None app = FastAPI() @app.post("/items/") async def create_item(item: Item): return item
This setup automatically validates the incoming JSON data against the Item
model.
You can use Pydantic models to define your API's response structure:
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str price: float app = FastAPI() @app.get("/items/{item_id}", response_model=Item) async def read_item(item_id: int): return {"name": "Foo", "price": 42.0}
This ensures that your API always returns the expected data structure.
FastAPI's dependency injection system is powerful and flexible:
from fastapi import FastAPI, Depends, HTTPException app = FastAPI() async def verify_token(token: str): if token != "secret-token": raise HTTPException(status_code=400, detail="Invalid token") return token @app.get("/items/") async def read_items(token: str = Depends(verify_token)): return {"token": token}
This example demonstrates how to use dependency injection for authentication.
FastAPI is built on top of Starlette, which means it has excellent support for asynchronous programming:
import asyncio from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): await asyncio.sleep(1) # Simulate an I/O-bound operation return {"message": "Hello, World!"}
This allows your API to handle many concurrent requests efficiently.
FastAPI automatically generates OpenAPI (formerly Swagger) documentation for your API. Visit /docs
to see the interactive API documentation and /redoc
for an alternative view.
FastAPI provides a clean way to handle errors:
from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 42: raise HTTPException(status_code=404, detail="Item not found") return {"item_id": item_id}
This example shows how to raise an HTTP exception with a custom status code and message.
FastAPI offers many advanced features, including:
Here's a quick example of setting up CORS:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
This setup allows all origins, which is suitable for development but should be restricted in production.
08/11/2024 | Python
13/01/2025 | Python
21/09/2024 | Python
08/11/2024 | Python
15/11/2024 | Python
05/10/2024 | Python
15/11/2024 | Python
17/11/2024 | Python
17/11/2024 | Python
14/11/2024 | Python
22/11/2024 | Python
14/11/2024 | Python