How to Use FastAPI for Python API Development

How to Use FastAPI for Python API Development

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+. It is based on standard Python-type hints and is designed to create RESTful APIs quickly and efficiently. In this article, we will explore how to use FastAPI for Python API development, covering installation, creating a basic API, and some advanced features.

Installation of FastAPI

To get started with FastAPI, you need to have Python installed on your system. FastAPI can be installed using pip. Additionally, you should install an ASGI server like Uvicorn to run your FastAPI application. Use the following commands:

pip install fastapi
pip install uvicorn

Creating a Basic API with FastAPI

Once FastAPI is installed, you can start creating a simple API. Create a new Python file, for example, main.py, and start coding:

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "World"}

In this code, we import FastAPI and create an instance of the application. The @app.get decorator creates a GET endpoint at the root URL. When a user accesses /, it returns a JSON response.

Running the FastAPI Application

To run your FastAPI application, use the Uvicorn server with the following command:

uvicorn main:app --reload

The --reload flag enables hot reloading, so changes you make to the code will automatically reflect in the app without restarting the server. Open your browser and go to http://127.0.0.1:8000 to see the response.

Defining Path Parameters and Query Parameters

FastAPI allows you to define parameters easily. Here’s how to create endpoints that use path and query parameters:

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}

This endpoint takes an item_id as a path parameter and an optional query parameter q. If a user visits /items/5?q=somequery, the app returns a JSON response with the specified item ID and query.

Request Body with Pydantic Models

FastAPI uses Pydantic for data validation and serialization. To create a request body with validation, define a Pydantic model:

from pydantic import BaseModel
class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None
@app.post("/items/")
def create_item(item: Item):
    return item

In this example, we define an Item model with three attributes. The @app.post decorator creates a POST endpoint that accepts an Item object in the request body, automatically validating the data.

Automatic Documentation

One of FastAPI's standout features is its automatic interactive API documentation. Once your app is running, you can visit:

  • http://127.0.0.1:8000/docs for Swagger UI
  • http://127.0.0.1:8000/redoc for ReDoc documentation

This documentation provides a quick way to test your API and understand its structure without needing to create separate documentation manually.

Advanced features of FastAPI

FastAPI also supports many advanced features such as dependency injection, background tasks, CORS handling, OAuth2, and more. This flexibility allows developers to build sophisticated APIs with relative ease.

Conclusion

FastAPI provides a robust and intuitive framework for building APIs in Python. Its speed, automatic documentation, and data validation capabilities make it an excellent choice for both beginners and advanced developers. Start your API development journey with FastAPI today and leverage its powerful features for your projects.