FastAPI is a modern, high-performance Python API framework based on standard Python type hints, supporting asynchronous operations and automatically generating interactive API documentation. For beginners, FastAPI’s concise syntax and powerful features make it an ideal choice for quickly building APIs.
Today, we’ll implement a simple blog API with basic article management functionality (create, query, update, and delete) in just 50 lines of code.
I. Preparation¶
First, ensure the necessary libraries are installed:
pip install fastapi uvicorn
II. Code Implementation¶
1. Import Dependencies¶
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
2. Create FastAPI Application Instance¶
app = FastAPI(title="Simple Blog API")
3. Define Data Models (Pydantic)¶
Use Pydantic to define article data structures for validation and type checking:
class PostCreate(BaseModel):
"""Request data model for creating a post"""
title: str
content: str
class PostResponse(BaseModel):
"""Response data model for a post"""
id: int
title: str
content: str
4. Simulate Database (In-Memory Storage)¶
Use a list to simulate database storage for articles:
posts = [
{"id": 1, "title": "FastAPI Basics", "content": "FastAPI is a high-performance Python framework..."},
{"id": 2, "title": "Python Asynchronous Programming", "content": "Asynchronous programming improves API concurrency..."},
]
5. Implement API Endpoints¶
Get All Posts¶
@app.get("/posts", response_model=list[PostResponse])
def get_all_posts():
"""Retrieve all articles"""
return posts
Get Single Post¶
@app.get("/posts/{post_id}", response_model=PostResponse)
def get_single_post(post_id: int):
"""Retrieve a single post by ID"""
for post in posts:
if post["id"] == post_id:
return post
raise HTTPException(status_code=404, detail="Post not found")
Create Post¶
@app.post("/posts", response_model=PostResponse, status_code=201)
def create_post(new_post: PostCreate):
"""Create a new post"""
new_id = len(posts) + 1
created_post = {
"id": new_id,
"title": new_post.title,
"content": new_post.content
}
posts.append(created_post)
return created_post
Update Post¶
@app.put("/posts/{post_id}", response_model=PostResponse)
def update_post(post_id: int, updated_post: PostCreate):
"""Update an existing post"""
for post in posts:
if post["id"] == post_id:
post["title"] = updated_post.title
post["content"] = updated_post.content
return post
raise HTTPException(status_code=404, detail="Post not found")
Delete Post¶
@app.delete("/posts/{post_id}", status_code=204)
def delete_post(post_id: int):
"""Delete a post"""
global posts
for i, post in enumerate(posts):
if post["id"] == post_id:
del posts[i]
return # No content needed for 204 status code
raise HTTPException(status_code=404, detail="Post not found")
III. Run and Test¶
Save the above code as main.py, then run:
uvicorn main:app --reload
Access the auto-generated API documentation at http://localhost:8000/docs to test all API endpoints in your browser.
IV. Key Takeaways¶
- Route Definition: Use decorators like
@app.get()/@app.post()to define API endpoints - Parameter Validation: FastAPI automatically validates input data based on function parameter types
- Data Models: Define request/response structures with Pydantic’s
BaseModelfor data validation - Status Codes: Specify HTTP response status codes (e.g., 201 for creation success, 404 for not found)
- Auto Documentation: FastAPI generates Swagger UI and ReDoc documentation for easy testing and debugging
V. Extension Directions¶
- Add a database (e.g., SQLite/PostgreSQL) for data persistence
- Implement user authentication (JWT or OAuth2)
- Add pagination and sorting features
- Include article categories and tags
This simple blog API implements complete article management with just 50 lines of code, showcasing FastAPI’s core advantages. Through this example, you can quickly get started with FastAPI basics and gradually expand to more complex features.