FastAPI Practical: Building RESTful APIs with GET and POST Methods

FastAPI is a modern, fast (high-performance) Python Web framework designed specifically for building RESTful APIs. It leverages standard Python type hints, automatically generates interactive API documentation (Swagger UI and ReDoc), and supports asynchronous operations, making it ideal for beginners to get started quickly.

1. Environment Setup

Before starting, we need to install FastAPI and an ASGI server (Uvicorn). Open your terminal and run the following command:

pip install fastapi uvicorn

Once installed, we can begin writing code.

2. First GET Endpoint: Get User List

The GET method is used to retrieve resources from the server. Here, we’ll create an endpoint to return a simulated list of users.

Code Example:

from fastapi import FastAPI

# Create a FastAPI application instance
app = FastAPI()

# Simulated database data
users = [
    {"id": 1, "name": "张三", "age": 20},
    {"id": 2, "name": "李四", "age": 25}
]

# Define a GET endpoint with path "/users"
@app.get("/users")
def get_users():
    """Get all user information"""
    return users  # Return the user list; FastAPI automatically converts it to JSON

Code Explanation:

  1. Import FastAPI: from fastapi import FastAPI imports the core framework class.
  2. Create Application Instance: app = FastAPI() instantiates the FastAPI object, and all subsequent endpoints are defined using this instance.
  3. Simulated Data: The users list simulates database data for testing purposes.
  4. Define GET Endpoint: The @app.get("/users") decorator specifies the access path as /users with the GET method. The def get_users() function handles the request, and its return value is automatically serialized to JSON and sent back to the client.

Effect Testing:

Run the code and execute the following command in the terminal:

uvicorn main:app --reload

(Note: main is your Python file name, app is the FastAPI instance name, and --reload restarts the server automatically when code changes are detected.)

Open your browser and visit http://localhost:8000/docs to see the interactive API documentation (Swagger UI) automatically generated by FastAPI. Click “Try it out” next to the GET /users endpoint and then “Execute” to view the returned user list.

3. Second POST Endpoint: Create New User

The POST method is used to submit data to the server. Here, we’ll create an endpoint to receive new user information and return the created user.

Code Example:

from fastapi import FastAPI
from pydantic import BaseModel  # For defining request data format

app = FastAPI()

# Simulated database data
users = [
    {"id": 1, "name": "张三", "age": 20},
    {"id": 2, "name": "李四", "age": 25}
]

# Define request data model: user information
class UserCreate(BaseModel):
    name: str  # Name, string type
    age: int   # Age, integer type

# Define a POST endpoint with path "/users"
@app.post("/users")
def create_user(user: UserCreate):
    """Create a new user"""
    # Generate a new user ID (max ID + 1 from existing users)
    new_id = max([u["id"] for u in users]) + 1 if users else 1
    new_user = {"id": new_id, **user.dict()}  # Unpack the dictionary
    users.append(new_user)
    return new_user  # Return the created user information

Code Explanation:

  1. Pydantic Model: The UserCreate class inherits from BaseModel to define the data format required for the POST request. It requires name (string) and age (integer), and FastAPI automatically validates input data types to prevent invalid data.
  2. POST Endpoint Definition: The @app.post("/users") decorator specifies the path as /users with the POST method. The def create_user(user: UserCreate) parameter user: UserCreate indicates the request body data type is the UserCreate model. FastAPI automatically parses the JSON data from the request and passes it to this parameter.
  3. Logic Handling: Generate a new user ID based on the maximum ID of existing users, add the new user information to the users list, and return the created user.

Effect Testing:

In Swagger UI, click on the POST /users endpoint and fill in the request body:

{
  "name": "王五",
  "age": 30
}

Click “Execute” to see the new user created and returned. Accessing the GET /users endpoint again will show Wang Wu’s information in the list.

4. Summary

Through the above two examples, we’ve created a simple RESTful API framework:

  1. GET Method: Used to retrieve resources (e.g., user list) with concise code that directly returns data.
  2. POST Method: Used to submit data (e.g., creating a new user), with data validation via Pydantic models to ensure correct input format.
  3. FastAPI Advantages: Automatic API documentation generation (no manual documentation writing), type hints and data validation to reduce errors, high performance and asynchronous support for strong future scalability.

Next, you can try extending the interface:
- Add path parameters (e.g., /users/{user_id} to get a single user)
- Implement PUT (update) and DELETE (delete) methods
- Integrate with a database (e.g., SQLite) for persistent storage

FastAPI has a gentle learning curve, with comprehensive and interactive documentation, making it an excellent entry-level framework for API development. Now, start practicing!

Xiaoye