Now tell me the basics of using FastAPI
- User
Now tell me the basics of using FastAPI
Assistant
Certainly! FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. Here's a basic overview of how to use FastAPI:
1. Installation
First, you need to install FastAPI and an ASGI server like
uvicornto run the application.pip install fastapi uvicorn2. Creating a Basic FastAPI Application
Here's a simple example of a FastAPI application:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}3. Running the Application
To run the application, use
uvicornfrom the command line:uvicorn main:app --reloadHere,
mainis the name of the Python file (without the.pyextension), andappis the instance ofFastAPI.4. Key Features
Path Parameters
You can define path parameters using curly braces
{}:@app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}Query Parameters
You can define query parameters using function parameters:
@app.get("/items/") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}Request Body
You can define request bodies using Pydantic models:
from pydantic import BaseModel from typing import Optional class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None @app.post("/items/") async def create_item(item: Item): return itemResponse Models
You can define response models to specify the structure of the response:
@app.get("/items/{item_id}", response_model=Item) async def read_item(item_id: int): return {"item_id": item_id, "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2}5. Dependencies
You can define dependencies to be used in your path operations:
from fastapi import Depends def get_query_token(token: str): if token != "jessica": raise HTTPException(status_code=400, detail="No Jessica token provided") return token @app.get("/items/") async def read_items(token: str = Depends(get_query_token)): return {"token": token}6. Middleware
You can add middleware to your FastAPI application:
from fastapi import FastAPI, Request from starlette.middleware.base import BaseHTTPMiddleware async def custom_middleware(request: Request, call_next): response = await call_next(request) response.headers["X-Process-Time"] = str(time.time()) return response app.add_middleware(BaseHTTPMiddleware, dispatch=custom_middleware)7. Background Tasks
You can perform background tasks using
BackgroundTasks:from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_log(message: str): with open("log.txt", "a") as log: log.write(message) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_log, f"Notification sent to {email}") return {"message": "Notification sent in the background"}8. Exception Handling
You can handle exceptions using
HTTPException:from fastapi import HTTPException, FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 0: raise HTTPException(status_code=404, detail="Item not found") return {"item_id": item_id}9. Documentation
FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc:
- Swagger UI:
http://127.0.0.1:8000/docs - ReDoc:
http://127.0.0.1:8000/redoc
10. Testing
You can test your FastAPI application using
httpxorrequests:import httpx async def test_read_main(): async with httpx.AsyncClient(app=app, base_url="http://test") as client: response = await client.get("/") assert response.status_code == 200 assert response.json() == {"Hello": "World"}Summary
FastAPI is designed to be easy to use, fast, and efficient. It leverages Python type hints to provide automatic data validation, serialization, and documentation. The framework is built on Starlette for the web parts and Pydantic for the data parts, making it a powerful tool for building modern web APIs.
- Swagger UI:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.