108 lines
3.9 KiB
Markdown
108 lines
3.9 KiB
Markdown
`FastAPI` is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. The key features of FastAPI include:
|
|
|
|
- **Fast**: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
|
|
- **Fast to code**: Great editor support. Completion everywhere. Less time debugging.
|
|
- **Easy**: Designed to be easy to use and learn. Less time reading docs.
|
|
- **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
|
|
- **Robust**: Get production-ready code. With automatic interactive documentation.
|
|
- **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI and JSON Schema.
|
|
|
|
Here's a concise reference guide for common use cases with `FastAPI`:
|
|
|
|
# `FastAPI` Reference Guide
|
|
|
|
## Installation
|
|
```
|
|
pip install fastapi[all]
|
|
```
|
|
This command installs FastAPI along with all its optional dependencies and features, including `uvicorn`, which is an ASGI server for running the application.
|
|
|
|
## Basic Usage
|
|
|
|
### Creating a Simple FastAPI Application
|
|
```python
|
|
from fastapi import FastAPI
|
|
|
|
app = FastAPI()
|
|
|
|
@app.get("/")
|
|
async def read_root():
|
|
return {"Hello": "World"}
|
|
```
|
|
|
|
### Running the Application
|
|
To run the application, use `uvicorn` from the command line:
|
|
```
|
|
uvicorn main:app --reload
|
|
```
|
|
Assuming your file is named `main.py` and your FastAPI app object is named `app`. The `--reload` flag enables auto-reload so the server will restart after code changes.
|
|
|
|
## Path Parameters
|
|
```python
|
|
@app.get("/items/{item_id}")
|
|
async def read_item(item_id: int):
|
|
return {"item_id": item_id}
|
|
```
|
|
Type hints are used to validate and convert path parameters.
|
|
|
|
## Query Parameters
|
|
```python
|
|
@app.get("/items/")
|
|
async def read_items(skip: int = 0, limit: int = 10):
|
|
return fake_items_db[skip : skip + limit]
|
|
```
|
|
|
|
## Request Body
|
|
```python
|
|
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
|
|
```
|
|
Pydantic models define the structure and validation of request bodies.
|
|
|
|
## Interactive API Documentation
|
|
FastAPI generates interactive API documentation (using Swagger UI and ReDoc) for your API, accessible from `/docs` and `/redoc`, once you start your application.
|
|
|
|
## Dependency Injection
|
|
```python
|
|
from fastapi import Depends, HTTPException
|
|
|
|
def fake_password_hasher(raw_password: str):
|
|
return "supersecret" + raw_password
|
|
|
|
def verify_password(username: str, password: str):
|
|
if username in fake_users_db and fake_password_hasher(password) == fake_users_db[username]["hashed_password"]:
|
|
return True
|
|
return False
|
|
|
|
async def get_current_username(username: str = Depends(verify_password)):
|
|
return username
|
|
```
|
|
FastAPI's dependency injection system allows you to have reusable dependencies that can have their own dependencies.
|
|
|
|
## Background Tasks
|
|
```python
|
|
from fastapi import BackgroundTasks
|
|
|
|
def write_log(message: str):
|
|
with open("log.txt", mode="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 for {email}")
|
|
return {"message": "Notification sent in the background"}
|
|
```
|
|
|
|
`FastAPI` is designed for building APIs that are easy to build, test, and use, with a focus on speed and type safety. This guide introduces the basics, but FastAPI's capabilities extend to more advanced features like security and authentication, more complex data modeling with Pydantic, WebSockets, GraphQL, and more, catering to modern web application development needs.
|
|
|
|
|
|
FastAPI's design and performance make it an attractive option for high-speed API services, providing a robust foundation for building reliable, efficient web services and applications. |