Introduction
FastAPI is a modern, high-performance web framework for building RESTful APIs with Python. Leveraging asynchronous programming and automatic data validation, FastAPI allows you to create scalable APIs quickly and efficiently. In this tutorial, you’ll learn how to create a real-world API that serves product data for an e-commerce scenario. We will cover endpoint creation, input validation using Pydantic models, running and testing the API, and exploring deployment strategies for a production-grade API.
Importing Required Packages
To keep our code organized and avoid repetition, we begin by importing the necessary packages. This ensures that all subsequent code blocks have access to the required libraries.
#|label: import-packages
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
Creating a Basic FastAPI App with Real-World Example Data
We’ll start by initializing a FastAPI application and creating endpoints. In our example, the API will serve product data for an e-commerce scenario.
Basic API Example
#|label: create-app
= FastAPI()
app
@app.get("/")
def read_root():
return {"message": "Welcome to the FastAPI Products API!"}
class Product(BaseModel):
id: int
str
name: float
price: str
category:
# Sample product data.
= [
products "id": 1, "name": "Wireless Mouse", "price": 29.99, "category": "Electronics"},
{"id": 2, "name": "Bluetooth Headphones", "price": 59.99, "category": "Electronics"},
{"id": 3, "name": "Coffee Maker", "price": 79.99, "category": "Home Appliances"},
{"id": 4, "name": "Electric Kettle", "price": 39.99, "category": "Home Appliances"},
{"id": 5, "name": "Smartphone Stand", "price": 19.99, "category": "Accessories"}
{
]
@app.get("/api/products", response_model=list[Product])
def get_products():
return products
if __name__ == "__main__":
# Run the application on port 8000 with debugging enabled.
import uvicorn
="0.0.0.0", port=8000) uvicorn.run(app, host
Running and Testing the API
To run your Flask API, execute your script using for example python api.py
.
Once your API is running, you can access it by visiting http://localhost:5000/
in your web browser.
Testing Your API
Test your API using cURL or Postman. For example, you can run the following commands in your terminal:
curl http://127.0.0.1:8000/
curl http://127.0.0.1:8000/api/products
These commands should return JSON responses with a welcome message and the product data, respectively.
Error Handling and Input Validation
FastAPI uses Pydantic models to validate input data. Additionally, proper error handling ensures your API responds gracefully to incorrect requests.
Example: Enhanced Endpoint with Validation
#|label: enhanced-endpoint
@app.get("/api/product/{product_id}", response_model=Product)
def get_product(product_id: int):
for product in products:
if product["id"] == product_id:
return product
raise HTTPException(status_code=404, detail="Product not found")
This endpoint retrieves a product by its ID, and if the product is not found, it raises a 404 error.
Deployment Strategies
For production deployment, consider these strategies:
Uvicorn with Gunicorn:
Deploy your FastAPI app using Gunicorn with Uvicorn workers for enhanced performance:gunicorn --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 your_script:app
Containerization:
Use Docker to containerize your application. A sample Dockerfile is shown below.
Dockerfile Example
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "--workers", "4", "--worker-class", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000", "your_script:app"]
Replace your_script
with the name of your Python file containing the FastAPI app.
Running and Testing the API (Recap)
Once deployed, use tools like cURL, Postman, or automated testing frameworks to verify your endpoints and ensure that your API behaves as expected in production.
Conclusion
FastAPI provides a modern, efficient, and easy-to-use framework for building RESTful APIs in Python. By following this guide, you have learned how to create a real-world API with product data, implement input validation and error handling, and explore deployment strategies for production-grade applications. With these skills, you can build scalable APIs that power modern web applications and data-driven services.
Further Reading
- Build Your First API with Flask
- Web Scraping with BeautifulSoup
- Python Automation: Scheduling and Task Automation
Happy coding, and enjoy building and deploying your RESTful API with FastAPI!
Reuse
Citation
@online{kassambara2024,
author = {Kassambara, Alboukadel},
title = {Building {REST} {APIs} with {FastAPI:} {A} {Modern} {Python}
{Framework}},
date = {2024-02-08},
url = {https://www.datanovia.com/learn/programming/python/tools/fastapi-rest-api.html},
langid = {en}
}