FastAPI is a modern, fast, web framework for building APIs with Python 3.6+ based on standard Python type hints. It is built on top of Starlette for the web parts and Pydantic for handling data validation and serialization. FastAPI is known for its high performance, automatic validation, easy-to-use API generation, and built-in OpenAPI and GraphQL support.
In this tutorial, we will cover the basics of setting up a FastAPI project, creating endpoints, handling parameters and request bodies, and more.
Step 1: Installation
First, you need to install FastAPI and Uvicorn, which is the ASGI server that FastAPI relies on for running your application. You can install them using pip:
$ pip install fastapi uvicorn
Step 2: Hello World
Let’s create a simple "Hello, World!" endpoint to get started. Create a new Python file, for example main.py
, and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
async def read_root():
return {"message": "Hello, World!"}
Step 3: Running the Application
To run your FastAPI application, use the Uvicorn command line interface (CLI) with the following command:
$ uvicorn main:app --reload
This will start the ASGI server and reload the server automatically when changes are made to your code.
Step 4: Setting Up Endpoints
FastAPI uses standard Python function annotations to define endpoints, paths, and request methods. Here’s an example of how to create a simple endpoint with a path parameter:
@app.get('/greet/{name}')
async def greet(name: str):
return {"message": f"Hello, {name}!"}
You can access the value of the name
parameter passed in the URL path by adding a parameter to the function with the same name as the path variable.
Step 5: Handling Request Bodies
FastAPI supports request and response models using Pydantic models. You can define request and response models as Python classes and use them as function annotations to handle request bodies. Here’s an example:
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
quantity: int
@app.post('/items/')
async def create_item(item: Item):
return {"name": item.name, "price": item.price}
In this example, the Item
class defines the structure of the request body, and the create_item
endpoint expects a JSON payload with the same structure for creating a new item.
Step 6: Automatic Data Validation
FastAPI automatically validates request data based on the type hints defined in the functions. If the request data does not match the expected types, FastAPI will return an error response with details about the validation errors.
Step 7: API Documentation
FastAPI automatically generates interactive API documentation based on the endpoint definitions and type hints. You can access the Swagger UI by visiting http://localhost:8000/docs
in your browser while the server is running.
Step 8: Deployment
You can deploy your FastAPI application in various ways, such as using Docker containers, serverless platforms like AWS Lambda, or traditional web servers like Nginx. Consult the FastAPI documentation for more details on deployment options.
This tutorial covers the basics of building APIs with FastAPI. FastAPI’s performance, ease of use, and automatic validation make it a great choice for building RESTful APIs in Python. Experiment with different endpoints, request types, and response models to explore the full potential of FastAPI. Happy coding!