In the ground since Wed Feb 24 2021
Last watered inWed Feb 24 2021
Fast API
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.
Benefits
- Fast: Very high performance, on par with NodeJS and Go.
- Type-checked (catches errors before runtime)
- Automatic API documentation
Anatomy of a FastAPI application
Defines what the API will return (automatic validation!)
Input validation using Pydantic models
Dependency injection (we'll cover this later)
Return values
- FastAPI automatically converts Python dictionaries to JSON
- Content-Type header will be application/json
Path parameters
Synchronous vs Asynchronous in FastAPI
FastAPI supports both synchronous and asynchronous endpoints. Understanding the difference is crucial for building efficient APIs.
Synchronous (Sync) Endpoints
Characteristics:
- Executes code line by line
- Waits for each operation to complete
- Blocks the thread while waiting
- Simpler to understand and debug
Asynchronous (Async) Endpoints
Characteristics:
- Can handle multiple operations concurrently
- Doesn't block while waiting for I/O
- More efficient for I/O-bound operations
- Uses async/await syntax
When to Use Each
Use Sync when:
- Doing CPU-intensive work
- Using libraries that don't support async
- Code is simple and doesn't involve waiting
Use Async when:
- Making HTTP requests
- Database operations (with async driver)
- File I/O operations
- Handling websockets
Common Pitfalls
- Blocking I/O in Async Functions (Bad)
- Proper Async Usage (Good)
API Documentation
FastAPI provides automatic interactive API documentation using:
Swagger UI
- Available at /docs
- Interactive documentation
- Try out API endpoints directly
- Shows request/response schemas
ReDoc
- Available at /redoc
- Alternative documentation view
- Better for reading and sharing
How Documentation is Generated
FastAPI uses your:
- Function names and docstrings
- Type hints
- Pydantic models
- Path operation decorators
Example with full documentation:
This generates:
- Endpoint description
- Request parameters
- Response model
- Example values
- Try it out functionality
Enhancing Documentation
- Tags - Group endpoints:
- Summary and Description:
- Response Description:
- Status Codes: