FastAPI Training: 10 3 Practice Exercises Explained
Key Concepts
Here are the key concepts related to the 10 3 practice exercises:
- Basic CRUD Operations: Creating, reading, updating, and deleting resources.
- Query Parameters and Path Parameters: Passing data to the API.
- Request Body and Response Formatting: Sending and receiving structured data.
- Error Handling: Managing exceptions and providing meaningful error messages.
- Database Interaction: Connecting and interacting with a database.
- Authentication and Authorization: Implementing security measures.
- File Handling: Managing file uploads and downloads.
- Third-Party Integrations: Integrating with external services.
- Background Tasks: Running tasks asynchronously.
- WebSocket Support: Enabling real-time communication.
1. Basic CRUD Operations
Basic CRUD operations involve creating, reading, updating, and deleting resources. These operations are fundamental to any RESTful API.
Example:
from fastapi import FastAPI app = FastAPI() items = [] @app.post("/items/") async def create_item(item: dict): items.append(item) return item @app.get("/items/{item_id}") async def read_item(item_id: int): return items[item_id] @app.put("/items/{item_id}") async def update_item(item_id: int, item: dict): items[item_id] = item return item @app.delete("/items/{item_id}") async def delete_item(item_id: int): items.pop(item_id) return {"status": "deleted"}
2. Query Parameters and Path Parameters
Query parameters are appended to the URL and are used to filter or sort data. Path parameters are part of the URL path and are used to identify a specific resource.
Example:
@app.get("/items/") async def read_items(q: str = None): return {"q": q} @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
3. Request Body and Response Formatting
The request body is used to send complex data structures to the API, typically in JSON format. Response formatting ensures that the data is structured in a way that is easily consumable by clients.
Example:
from pydantic import BaseModel class Item(BaseModel): name: str description: str = None price: float tax: float = None @app.post("/items/") async def create_item(item: Item): return {"item": item}
4. Error Handling
Error handling involves managing exceptions and providing meaningful error messages. FastAPI provides built-in support for handling HTTP exceptions.
Example:
from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id < 0: raise HTTPException(status_code=400, detail="Item ID must be positive") return {"item_id": item_id}
5. Database Interaction
Database interaction involves connecting to and interacting with a database. FastAPI can work with various ORMs like SQLAlchemy.
Example:
from fastapi import FastAPI from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker DATABASE_URL = "sqlite:///./test.db" engine = create_engine(DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get("/items/{item_id}") async def read_item(item_id: int, db = Depends(get_db)): item = db.query(Item).filter(Item.id == item_id).first() return {"item": item}
6. Authentication and Authorization
Implementing security measures involves using OAuth2 and JWT for authentication and defining roles for authorization.
Example:
from fastapi import FastAPI, Depends, HTTPException from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def get_current_user(token: str = Depends(oauth2_scheme)): if not token: raise HTTPException(status_code=401, detail="Not authenticated") return {"user": "authenticated_user"} @app.get("/secure") async def secure_endpoint(user: dict = Depends(get_current_user)): return {"message": "This is a secure endpoint", "user": user}
7. File Handling
Managing file uploads and downloads involves using FastAPI's built-in support for file handling.
Example:
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(...)): return {"filename": file.filename} @app.get("/download/{file_name}") async def download_file(file_name: str): return FileResponse(file_name)
8. Third-Party Integrations
Integrating with external services involves using HTTP clients like Requests or HTTPX to interact with third-party APIs.
Example:
from fastapi import FastAPI import httpx app = FastAPI() @app.get("/weather/{city}") async def get_weather(city: str): async with httpx.AsyncClient() as client: response = await client.get(f"https://api.weather.com/v2/weather/{city}") return response.json()
9. Background Tasks
Running tasks asynchronously involves using FastAPI's background tasks to handle long-running operations.
Example:
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def send_notification(email: str): # Send email notification pass @app.post("/notify/{email}") async def notify_user(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(send_notification, email) return {"message": "Notification sent in the background"}
10. WebSocket Support
Enabling real-time communication involves using WebSockets to establish a two-way communication channel between the client and server.
Example:
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}")
Analogies
Think of basic CRUD operations as the four basic actions in a library (add, retrieve, update, remove books). Query parameters and path parameters are like the search filters and book IDs in a library catalog. Request body and response formatting are like the book request form and the returned book list. Error handling is like a librarian's guidance when you make a mistake. Database interaction is like the storage room where books are kept. Authentication and authorization are like security checkpoints in a library. File handling is like managing digital books in an e-library. Third-party integrations are like connecting the library to other libraries. Background tasks are like maintenance crews working on the library. WebSocket support is like a two-way communication system in the library.
By mastering these concepts, you can effectively build and deploy real-world projects using FastAPI, ensuring they are robust, secure, and scalable.