How to Build RESTful APIs with FastAPI: A Modern Guide
Building High-Performance APIs with Python's FastAPI
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use and easy to learn, while also providing the performance of asynchronous code. In this blog, we'll explore the key features of FastAPI, its benefits, and how to build a simple RESTful API using this framework.
Why Choose FastAPI?
FastAPI is quickly becoming the go-to choice for developers when building APIs for several reasons:
High Performance:
- FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts. This combination results in performance that is comparable to Node.js and Go APIs.
Ease of Use:
- With its straightforward syntax and automatic interactive API documentation, FastAPI is incredibly user-friendly. It automatically generates OpenAPI and JSON Schema documentation.
Type Safety:
- FastAPI leverages Python type hints, which help catch errors early and make your code more robust and maintainable.
Asynchronous Capabilities:
- Built-in support for async and await, making it easy to write asynchronous code and manage concurrency.
Automatic Validation:
- Pydantic models ensure data validation and parsing are automatic and efficient.
Setting Up FastAPI
Before you start building your API, you need to install FastAPI and an ASGI server, such as Uvicorn, to run your application.
pip install fastapi uvicorn
Building Your First FastAPI Application
Let's start by creating a simple API that allows users to perform CRUD operations on a list of items.
Step 1: Import FastAPI and Create an Instance
from fastapi import FastAPI
app = FastAPI()
Step 2: Define a Pydantic Model for Your Data
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
Step 3: Create In-Memory Storage for Items
items = {}
Step 4: Define the API Endpoints
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
item_id = len(items) + 1
items[item_id] = item
return item
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
return items[item_id]
@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, item: Item):
items[item_id] = item
return item
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
del items[item_id]
return {"message": "Item deleted successfully"}
Step 5: Run Your Application
To run the application, use the Uvicorn server:
uvicorn main:app --reload
Visit http://127.0.0.1:8000
in your browser. You will see the automatically generated interactive API documentation at http://127.0.0.1:8000/docs
.
Advanced Features of FastAPI
FastAPI offers several advanced features that make it a powerful tool for API development:
Dependency Injection:
- FastAPI's dependency injection system allows you to define dependencies that can be automatically resolved and injected into your route handlers.
Background Tasks:
- FastAPI supports background tasks, which allow you to perform operations after returning a response.
OAuth2 and JWT Authentication:
- FastAPI provides built-in support for OAuth2 with JWT tokens, making it easy to implement secure authentication mechanisms.
CORS (Cross-Origin Resource Sharing):
- Easily enable CORS for your application to allow or restrict resources on a web server.
Middleware:
- FastAPI supports middleware to modify requests and responses globally.
Example: Adding Dependency Injection
Let's enhance our API by adding a simple dependency that provides a database session.
from fastapi import Depends
from sqlalchemy.orm import Session
from database import SessionLocal, engine, Base
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/items/", response_model=Item)
async def create_item(item: Item, db: Session = Depends(get_db)):
db_item = ItemModel(**item.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
Conclusion
Feel free to explore FastAPI's extensive documentation to discover more features and best practices. Happy coding!