FastAPI¶
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
FastAPI is a modern Python web framework that leverage the latest Python features to provide you with a simple way to build APIs. It is based on standard Python type hints and is designed to be easy to use and learn. FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts.
Quick Understanding¶
- 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: Increase the speed to develop features by about 200% to 300%.
- Fewer bugs: Reduce about 40% of human (developer) induced errors. *
- 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 standard Python type hints. It is fully type-checkable.
- Fully asynchronous: Supports type hints natively. Performant execution.
- Automatic interactive API documentation: Swagger UI, ReDoc, and OpenAPI.
Installation¶
You can install FastAPI using pip:
Hello world¶
Here is a simple example of a FastAPI application:
=== "hello world"
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
# To run the app use following command where hello is the name of the file specify port using --port
uvicorn hello:app --reload --port 8000
URL Path¶
=== "url path"
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_items(item_id: int, q: str = None):
return {"items_id": item_id, q: q}
Query Parameters¶
=== "URI parameter"
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/products")
def read_products(product_id: int, details: bool = False):
return {"product_id": product_id, "details": details}
Request Body¶
=== "request body"
from fastapi import FastAPI
# Data model validation using Pydantic
from pydantic import BaseModel
class Item(BaseModel):
name: str
descriptions: str = None
price: float
tax: float = None
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/items/")
def create_item(item: Item):
print(item, type(item))
return item.dict()
FormData and File Uploads¶
=== "form data"
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/uploadfile")
async def file_upload(file: UploadFile = File(...)):
return {"filename": file.filename}
Authentication¶
=== "authentication"