Building Web APIs with FastAPI in Python

Introduction

In today’s fast-paced development landscape, building high-performance web APIs is crucial for many applications.

FastAPI, a modern, lightweight, and highly efficient web framework, is gaining popularity among Python developers for its simplicity and speed.

In this article, we will explore how to use FastAPI to create robust and scalable web APIs, along with numerous code examples to illustrate its usage.

What is FastAPI?

FastAPI is a modern Python web framework that is built on top of Starlette, a high-performance asynchronous web framework. It leverages the latest features of Python 3.7+ and provides a simple and intuitive way to build web APIs quickly. Some key features of FastAPI include:

  • Fast: FastAPI is one of the fastest web frameworks available for Python, owing to its asynchronous support and efficient request handling.
  • Type hints: FastAPI leverages Python’s type hinting feature to provide automatic data validation and documentation, making it developer-friendly.
  • API documentation: FastAPI generates interactive API documentation automatically based on the defined API routes and data models.
  • Easy integration: FastAPI seamlessly integrates with other popular Python libraries and frameworks, such as SQLAlchemy, Pydantic, and OAuth2.
  • WebSocket support: FastAPI provides support for bidirectional communication through WebSockets, making it suitable for real-time applications.

Now, let’s dive into the practical examples and explore how to use FastAPI effectively.

Installation

To get started with FastAPI, we first need to install it. Open your terminal and run the following command:

pip install fastapi

Additionally, we will also install uvicorn, a lightning-fast ASGI server that is highly recommended for running FastAPI applications:

pip install uvicorn

With FastAPI and uvicorn installed, we are ready to build our first API.

Creating a Simple API

Let’s begin by creating a simple API endpoint that returns a JSON response. Create a new Python file called main.py and import the necessary modules:

from fastapi import FastAPI

app = FastAPI()

We create an instance of the FastAPI class, which will be our main application. Now, let’s define our API route:

@app.get("/")
def read_root():
    return {"Hello": "World"}

In the above code, we use the @app.get decorator to define an HTTP GET endpoint for the root URL (“/”). The read_root() function is the handler for this endpoint, which simply returns a JSON response with the message “Hello, World”.

To run the application, use the following command in your terminal:

uvicorn main:app --reload

Now, if you visit http://localhost:8000 in your browser, you should see the API response: {"Hello": "World"}.

Congratulations! You have just created your first FastAPI application.

Handling Path Parameters

FastAPI provides a convenient way to handle path parameters in API routes. Let’s modify our previous example to include a dynamic path parameter:

@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"user_id": user_id}

In the updated code, we added a new route /users/{user_id}, where {user_id} acts as a placeholder for the actual user ID. The get_user() function now takes an additional parameter user_id of type int. FastAPI automatically validates the parameter type and ensures it matches the specified type hint.

When you run the application and visit http://localhost:8000/users/123, you will receive the response {"user_id": 123}.

Request Body and Data Validation

Handling request bodies is a common requirement in web APIs. FastAPI makes it easy to define request models using Pydantic, a powerful data validation library. Let’s create an API endpoint that accepts a JSON request body and validates its structure:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
def create_item(item: Item):
    return item

In the code above, we defined a Item class as a Pydantic model with two fields: name of type str and price of type float. The create_item() function takes an instance of the Item model as its parameter. FastAPI automatically validates the request data against the defined model and ensures the expected structure and types.

To test the API, you can use tools like cURL or send a POST request with JSON data using a tool like Postman or curl:

curl -X POST -H "Content-Type: application/json" -d '{"name": "Example", "price": 9.99}' http://localhost:8000/items/

The API will respond with the same JSON data received in the request body.

API Documentation

FastAPI generates comprehensive API documentation automatically, based on the defined routes and models. To access the documentation, visit http://localhost:8000/docs in your browser.

The documentation provides an interactive interface to explore the available API endpoints, view request and response schemas, and even test the API directly within the browser.

Conclusion

FastAPI is a powerful and developer-friendly web framework for building high-performance web APIs in Python. Its simplicity, speed, and built-in features, such as automatic data validation and API documentation, make it an excellent choice for a wide range of applications.

In this article, we covered the basics of using FastAPI, including creating API endpoints, handling path parameters, validating request data, and generating API documentation. By exploring these examples, you should now have a solid foundation to start building your own robust and scalable web APIs using FastAPI.

Remember to consult the official FastAPI documentation for more advanced features and best practices. Happy coding!

Jan Horecny

Jan Horecny

Jan Horecny is a highly skilled Lead Senior Developer at GALTON Brands, specializing in WordPress development, PHP, and databases. With a keen eye for detail and a passion for creating exceptional online experiences, Jan consistently delivers top-notch solutions that drive results. His extensive expertise in WordPress, coupled with his deep understanding of PHP and database management, enables him to design and develop robust, scalable, and user-friendly websites.