FastAPI Practical: Building RESTful APIs with GET and POST Methods

Why Choose FastAPI?

In today’s web development, building efficient and easy-to-use APIs has become increasingly important. FastAPI is a modern Python-based web framework with several standout advantages:

  • High Performance: Built on Starlette and Pydantic, it performs nearly as well as Node.js and Go
  • Automatic API Documentation: No additional tools needed; comes with Swagger UI and ReDoc
  • Type Hint Support: Leverages Python type annotations to automatically generate interface specifications and data validation
  • Usability: Clean code with a gentle learning curve, perfect for beginners to get started quickly

Environment Setup

First, install FastAPI and a server to run it:

pip install fastapi uvicorn

uvicorn is FastAPI’s recommended ASGI server for running your API application.

Quick Start: Your First API

Let’s start with the simplest example, creating an interface that returns a welcome message:

from fastapi import FastAPI

# Create a FastAPI application instance
app = FastAPI(title="FastAPI Example")

# Define a GET request endpoint at path "/"
@app.get("/")
async def root():
    return {"message": "Welcome to FastAPI! Visit /docs to see API documentation"}

How to Run: Execute the following command in your terminal. The server will start at http://localhost:8000:

uvicorn main:app --reload

main is the current Python filename, app is the FastAPI instance we created, and --reload enables auto-reloading during development.

GET Method Practical: Retrieving Data

Let’s build a user management system and first implement the “get user information” feature.

1. Get User by ID (Path Parameters)

from fastapi import FastAPI

app = FastAPI()

# Simulated database: list of users
fake_users_db = [
    {"id": 1, "name": "Zhang San", "age": 25},
    {"id": 2, "name": "Li Si", "age": 30},
    {"id": 3, "name": "Wang Wu", "age": 28}
]

# Define GET request with path parameter "/users/{user_id}"
@app.get("/users/{user_id}")
async def get_user(user_id: int):  # user_id is a path parameter with integer type
    """Get user information by ID"""
    # Search for the user in the simulated database
    for user in fake_users_db:
        if user["id"] == user_id:
            return user
    return {"error": "User not found"}

Key Points:
- Path parameters are declared with {user_id}, and the function parameter is directly user_id: int (FastAPI automatically validates the type)
- Dictionaries returned by the function are automatically serialized to JSON by FastAPI
- Path parameter type validation: If a non-integer value is passed, it automatically returns a 422 error

2. User Filtering with Query Parameters

Sometimes we need to filter users by conditions, such as searching by name:

@app.get("/users/filter")
async def filter_users(name: str = None, age: int = None):
    """Filter users by name and/or age"""
    result = []
    for user in fake_users_db:
        if (name is None or user["name"] == name) and (age is None or user["age"] == age):
            result.append(user)
    return result

Testing Method: Visit http://localhost:8000/users/filter?name=Zhang San to get all users named “Zhang San”.

POST Method Practical: Submitting Data

Use the POST method to create new users by receiving JSON-formatted user data.

1. Define Data Model

FastAPI recommends using Pydantic models to define request data structures:

from pydantic import BaseModel

# Define a model for user creation data
class UserCreate(BaseModel):
    name: str
    age: int
    email: str = None  # Optional field

2. Implement User Creation Endpoint

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.post("/users")
async def create_user(user: UserCreate):
    """Create a new user"""
    # Simulate user ID generation (use database auto-increment in production)
    new_id = max([u["id"] for u in fake_users_db], default=0) + 1
    new_user = {
        "id": new_id,
        "name": user.name,
        "age": user.age,
        "email": user.email
    }
    fake_users_db.append(new_user)
    return {"message": "User created successfully", "user": new_user}

Key Points:
- Use the @app.post decorator to define a POST endpoint
- Receive JSON data via user: UserCreate; FastAPI automatically validates the data format
- Pydantic models provide robust data validation (type checking, required field validation, etc.)

Automatic API Documentation

One of FastAPI’s most useful features is its automatic API documentation. After starting the server:

  • Visit http://localhost:8000/docs to view Swagger UI (interactive documentation)
  • Visit http://localhost:8000/redoc to view ReDoc documentation

In Swagger UI, you can directly input parameters and click “Try it out” to test endpoints, making it ideal for development and debugging.

Complete Code Example

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

# Create application instance
app = FastAPI(title="User Management API")

# Simulated database
fake_users_db = [
    {"id": 1, "name": "Zhang San", "age": 25, "email": "zhangsan@example.com"},
    {"id": 2, "name": "Li Si", "age": 30, "email": "lisi@example.com"}
]

# Define user creation model
class UserCreate(BaseModel):
    name: str
    age: int
    email: str = None

# Root endpoint
@app.get("/")
async def root():
    return {"message": "Welcome to the User Management API! Visit /docs for documentation"}

# Get user by ID
@app.get("/users/{user_id}")
async def get_user(user_id: int):
    """Get user information by ID"""
    for user in fake_users_db:
        if user["id"] == user_id:
            return user
    raise HTTPException(status_code=404, detail="User not found")

# Filter users
@app.get("/users/filter")
async def filter_users(name: str = None, age: int = None):
    """Filter users by name and/or age"""
    result = []
    for user in fake_users_db:
        if (name is None or user["name"] == name) and (age is None or user["age"] == age):
            result.append(user)
    return result

# Create user
@app.post("/users")
async def create_user(user: UserCreate):
    """Create a new user"""
    new_id = max([u["id"] for u in fake_users_db], default=0) + 1
    new_user = {
        "id": new_id,
        "name": user.name,
        "age": user.age,
        "email": user.email
    }
    fake_users_db.append(new_user)
    return {"message": "User created successfully", "user": new_user}

Summary

Through this article, we’ve learned:

  1. Basic installation and startup of FastAPI
  2. Using GET methods to handle path and query parameters
  3. Using POST methods to handle JSON data (with Pydantic models)
  4. Testing endpoints using automatically generated API documentation

FastAPI’s core advantages include: type hints, automatic data validation, interactive documentation, and excellent performance. For beginners, it offers an “immediate use” development experience, allowing you to quickly build reliable RESTful APIs.

Now, try extending this example: add PUT (update user) and DELETE (delete user) endpoints, or connect to a real database to experience the complete API development process!

Xiaoye