Developing APIs with Python and FastAPI

A Practical Guide

Adrià Serra
Towards Dev

--

Photo by Emile Perron on Unsplash

FastAPI is a modern, fast, and efficient Python framework for building APIs. With its intuitive syntax, automatic documentation generation, and built-in validation, FastAPI has gained popularity among developers. In this blog post, we will explore the fundamentals of API development using FastAPI and provide practical code snippets to help you get started.

Setting Up a Basic FastAPI Server

Let’s begin by setting up a primary FastAPI server. FastAPI leverages Python’s type annotations to generate documentation and perform data validation automatically.

from fastapi import FastAPI

app = FastAPI()

@app.get("/api/v1/hello")
def hello():
return {"message": "Hello, World!"}

In this code snippet, we import the FastAPI class, create an instance of the FastAPI application, and define a route using the @app.get decorator. The hello() function is executed when the /api/v1/hello endpoint is accessed, and it returns a JSON response containing a "Hello, World!" message.

Handling Path Parameters and Query Parameters

FastAPI provides straightforward ways to handle path parameters and query parameters.

from fastapi import FastAPI

app = FastAPI()

@app.get("/api/v1/greet/{name}")
def greet(name: str):
return {"message": f"Hello, {name}!"}

@app.get("/api/v1/items/")
def get_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}

In this example, we define two routes. The first route /api/v1/greet/{name} includes a path parameter {name} automatically extracted and passed as an argument to the greet() function. The second route /api/v1/items/ includes query parameters skip and limit, which have default values. FastAPI handles the type conversion and validation automatically.

Handling Request Payloads

FastAPI makes it easy to handle request payloads, including JSON payloads.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Employee(BaseModel):
name: str
age: int

@app.post("/api/v1/employees")
def add_employee(employee: Employee):
# Save the employee data to the database
return {"message": "Employee added successfully."}

In this code snippet, we define a data model Employee using Pydantic, a powerful data validation library integrated with FastAPI. The add_employee() function takes a employee parameter of type Employee, and FastAPI automatically parses and validates the request payload against the defined model.

Deployment

Deploying a FastAPI application is a straightforward process, and there are multiple options available depending on your specific requirements and infrastructure. Here are a few common approaches to deploying a FastAPI application:

  1. Local Development: During the development phase, you can run your FastAPI application locally using the built-in development server provided by FastAPI. Simply execute the uvicorn command, passing the name of your main Python file and the app instance as arguments. For example:
import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/api/v1/hello")
def hello():
return {"message": "Hello, World!"}

if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
python main.py

This command starts the development server and automatically reloads the application whenever you make code changes, which is convenient for local testing and development.

  1. Containerization: Containerization with Docker is a popular option for deploying FastAPI applications. Docker allows you to package your application along with its dependencies into a container, making it portable and easy to deploy across different environments. You can create a Dockerfile that specifies the necessary dependencies and build an image. Then, you can run the image as a container on any platform that supports Docker.
  2. Cloud Platforms: Cloud platforms like Heroku, AWS, Google Cloud Platform, and Azure provide simple and scalable options for deploying FastAPI applications. These platforms offer various services and tools to host and manage your application, such as serverless functions, container services, and platform-as-a-service (PaaS) offerings. You can choose the platform that aligns with your requirements, follow their deployment guidelines, and deploy your FastAPI application effortlessly.
  3. Virtual Machines or Bare Metal Servers: If you have your own infrastructure or prefer more control over the deployment environment, you can deploy your FastAPI application on a virtual machine or a bare metal server. You would typically set up a production-grade web server like Nginx or Apache as a reverse proxy to handle incoming requests and route them to your FastAPI application running on a specific port.

Remember to consider factors such as scalability, security, and monitoring while deploying your FastAPI application. Each deployment option has its own advantages and considerations, so choose the one that best suits your project’s needs.

Automatic Documentation

One of the standout features of FastAPI is its automatic documentation generation. With FastAPI, you don’t have to spend extra time and effort creating API documentation separately. FastAPI leverages the power of Python’s type annotations and generates interactive and comprehensive API documentation automatically.

By running your FastAPI server and navigating to the /docs route in your browser, you are greeted with an intuitive and user-friendly documentation page. This documentation provides detailed information about each API endpoint, including the expected request parameters, response schemas, and example requests and responses.

FastAPI also integrates with the OpenAPI standard, allowing you to export your API documentation in JSON format or utilize popular API documentation tools like Swagger UI. This makes it easy to share your API documentation with teammates, clients, or the wider developer community.

The automatic documentation feature not only saves development time but also improves collaboration and reduces errors. Developers can refer to the documentation to understand the API structure, available endpoints, and data formats, enabling them to build client applications that seamlessly integrate with your API.

With FastAPI’s automatic documentation, you can ensure that your API is well-documented, self-explanatory, and easily accessible to anyone who needs to interact with it.

Conclusion

FastAPI is a powerful framework for building APIs with Python. With its intuitive syntax, automatic documentation generation, and built-in validation, FastAPI simplifies API development and enhances productivity. In this blog post, we covered the basics of API development using FastAPI, including setting up a server, handling path parameters, query parameters, and request payloads. Armed with these code snippets, you can now embark on developing robust and efficient APIs using FastAPI. Happy coding!

If you liked this post, I usually post about maths, machine learning, and starting to publish about data engineering and programming. Do not hesitate to follow my profile to get notified about new posts

https://medium.com/@crunchyml

--

--

Data scientst, this account will share my blog post about statistic, probability, machine learning and deep learming. #100daysofML