This will include Pydantic and Starlette as well as their required dependencies like httpx, jinja2, python-multipart, uvicorn, fastapi-cli, orjson (optional), ujson (optional).
2. Define your API endpoints using FastAPI’s decorators to specify the input parameters, output data types, and other options. For example:
# Importing necessary modules
from fastapi import FastAPI # Importing FastAPI module
# Creating an instance of FastAPI
app = FastAPI()
# Defining a class for the item with its attributes
class Item(BaseModel):
name: str # Name of the item, with data type string
price: float # Price of the item, with data type float
is_offer: Union[bool, None] = None # Optional attribute for whether the item is on offer, with data type boolean or None
# Defining a function for the root endpoint
@app.get("/")
def read_root():
return {"Hello": "World"} # Returns a dictionary with a "Hello" key and "World" value
# Defining a function for the endpoint with item_id as a path parameter and q as a query parameter
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q} # Returns a dictionary with the item_id and q values
# Defining a function for the endpoint with item_id as a path parameter and item as a request body
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id} # Returns a dictionary with the item name and item_id from the request body
3. Run the FastAPI server using uvicorn and your app instance:
# This script is used to run the FastAPI server using uvicorn and the app instance.
# The first line uses the "uvicorn" command to run the server, followed by the name of the main file and the app instance.
# The "--reload" flag is used to automatically reload the server when changes are made to the code.
uvicorn main:app --reload
4. Access your API endpoints at http://localhost:8000/docs or http://localhost:8000/redoc to view the interactive documentation, which will automatically update as you modify your code.
5. FastAPI provides automatic validation of input data and conversion between Python types and network formats like JSON, Path parameters, Query parameters, Cookies, Headers, Forms, Files, etc.
6. You can also use Pydantic to define more complex models for deeply nested JSON objects.
7. FastAPI supports security features like OAuth2 with JWT tokens and HTTP Basic auth.
8. Performance-wise, FastAPI applications running under Uvicorn are one of the fastest Python frameworks available according to independent TechEmpower benchmarks.
9. For more information on how to use FastAPI, see the Tutorial User Guide or check out the documentation for additional features like WebSockets, CORS, and cookie sessions.