Building a Simple REST API with FastAPI and Python
FastAPI is a modern, high-performance web framework for building APIs with Python. It is known for its speed, automatic documentation, and easy-to-use syntax. Compared to Flask and Django, FastAPI is significantly faster due to its asynchronous capabilities.
In this guide, we will build a simple REST API with FastAPI, covering installation, route creation, request handling, and API documentation.
1. Why Use FastAPI?
FastAPI offers several advantages over other Python frameworks:
✔ Fast execution → Uses asynchronous programming (async/await) for better performance.
✔ Automatic API documentation → OpenAPI and Swagger UI are built-in.
✔ Type validation → Uses Python type hints for request validation.
✔ Minimal boilerplate → Simple syntax makes development faster.
FastAPI is ideal for real-time applications, microservices, and machine learning APIs.
2. Installing FastAPI and Uvicorn
To get started, install FastAPI and Uvicorn (an ASGI server to run FastAPI apps):
pip install fastapi uvicorn
Verify installation:
python -c "import fastapi; print(fastapi.__version__)"
3. Creating a Basic FastAPI Application
Create a new file called main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"message": "Welcome to my FastAPI!"}
Run the server using Uvicorn:
uvicorn main:app --reload
Open your browser and go to:
- API Home: http://127.0.0.1:8000/
- Interactive Docs: http://127.0.0.1:8000/docs (Swagger UI)
- Alternative Docs: http://127.0.0.1:8000/redoc (ReDoc)
FastAPI automatically generates API documentation for you.
4. Adding API Endpoints
Let’s add more routes to handle GET, POST, PUT, and DELETE requests.
A. Creating a Simple API with Data
We’ll create a fake database of books.
from fastapi import FastAPI
from typing import List
app = FastAPI()
books = [
{"id": 1, "title": "1984", "author": "George Orwell"},
{"id": 2, "title": "Brave New World", "author": "Aldous Huxley"},
]
@app.get("/books", response_model=List[dict])
def get_books():
return books
B. Getting a Book by ID
We use path parameters to fetch a single book:
@app.get("/books/{book_id}")
def get_book(book_id: int):
for book in books:
if book["id"] == book_id:
return book
return {"error": "Book not found"}
C. Creating a New Book
A POST request allows users to add books.
from pydantic import BaseModel
class Book(BaseModel):
title: str
author: str
@app.post("/books")
def create_book(book: Book):
new_book = {"id": len(books) + 1, "title": book.title, "author": book.author}
books.append(new_book)
return new_book
D. Updating an Existing Book
A PUT request modifies an existing book.
@app.put("/books/{book_id}")
def update_book(book_id: int, book: Book):
for b in books:
if b["id"] == book_id:
b["title"] = book.title
b["author"] = book.author
return b
return {"error": "Book not found"}
E. Deleting a Book
A DELETE request removes a book.
@app.delete("/books/{book_id}")
def delete_book(book_id: int):
global books
books = [b for b in books if b["id"] != book_id]
return {"message": "Book deleted"}
5. Validating API Requests
FastAPI automatically validates data based on Pydantic models.
For example, if we try to create a book without a title, FastAPI returns an error:
{
"detail": [
{
"loc": ["body", "title"],
"msg": "field required",
"type": "value_error.missing"
}
]
}
This built-in validation prevents incorrect data entry.
6. Running and Testing the API
Start the server again:
uvicorn main:app --reload
Test the endpoints:
| Method | URL | Function |
|---|---|---|
| GET | /books | Get all books |
| GET | /books/1 | Get book by ID |
| POST | /books | Add a new book |
| PUT | /books/1 | Update book details |
| DELETE | /books/1 | Remove a book |
Use Postman, Curl, or FastAPI Swagger UI to test API requests.
7. Deploying FastAPI with Uvicorn and Vercel
To deploy on Vercel, create a vercel.json file:
{
"builds": [{ "src": "main.py", "use": "@vercel/python" }],
"routes": [{ "src": "/(.*)", "dest": "main.py" }]
}
Then, deploy with:
vercel --prod
Your FastAPI app is now live on the web.
8. Why Use FastAPI Over Flask?
| Feature | FastAPI | Flask |
|---|---|---|
| Speed | 🚀 Faster (Async) | 🐢 Slower (Sync) |
| Type Checking | ✅ Yes | ❌ No |
| Automatic Docs | ✅ Yes | ❌ No |
| Built-in Validation | ✅ Yes | ❌ No |
| Best for APIs | ✅ Yes | ✅ Yes |
FastAPI is 40% faster than Flask and ideal for modern web APIs.
Conclusion
FastAPI is a powerful and efficient framework for building APIs with minimal code and high performance. With built-in validation, automatic documentation, and async support, it simplifies API development.
Key Takeaways
✔ Simple, fast API development. ✔ Automatic Swagger UI for documentation. ✔ Data validation using Pydantic. ✔ Supports async and serverless deployment.
Try building your first FastAPI project today!
Disclaimer
Article written with the help of AI.
This blog post is for informational purposes only and is not affiliated with or endorsed by any mentioned company. References are for discussion, not promotion. Some information may be inaccurate, readers should verify independently before making decisions.