Python FastAPI ¶
FastAPI1 is a modern, fast (high-performance), web framework for building APIs.
Info
FastAPI takes advantage of Python type hints.
Features
Fast, high performance, fast to code, intuitive, short, robust, standards-based
Installation¶
pip install fastapi
Interactive API Docs (automatic)¶
Swagger UI2 | ReDoc3 |
---|---|
http://127.0.0.1:8000/docs | http://127.0.0.1:8000/redoc |
HTTP Methods¶
Note
FastAPI works with the OpenAPI Schema.
HTTP Method | Description | FastAPI Decorator |
---|---|---|
GET | Read data | @app.get() |
POST | Create data | @app.post() |
PUT | Update data | @app.put() |
DELETE | Delete data | @app.delete() |
Methods in FastAPI are defined with the @app.<method>()
decorator.
@app.get("/")
def read_root():
return {"message": "Hello World"}
Example¶
from typing import Union
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: Union[str, None] = None):
return {"item_id": item_id, "q": q}
uvicorn main:app --reload