从零开始构建一个 RESTful API

作者:

RESTful API 是现代 Web 开发中最常用的接口设计风格。本文将用 Python + FastAPI 从零构建一个完整的 RESTful API。

什么是 RESTful API

REST(Representational State Transfer)是一种架构风格,核心思想是:

  • 用 URL 表示资源
  • 用 HTTP 方法表示操作(GET/POST/PUT/DELETE)
  • 用 HTTP 状态码表示结果
  • 无状态通信

项目搭建

首先安装依赖:

pip install fastapi uvicorn sqlalchemy

创建项目结构:

myapi/
  main.py
  database.py
  models.py
  schemas.py
  crud.py

定义数据模型

使用 SQLAlchemy 定义一个简单的文章模型:

from sqlalchemy import Column, Integer, String, Text
from database import Base

class Post(Base):
    __tablename__ = "posts"
    id = Column(Integer, primary_key=True)
    title = Column(String(100), nullable=False)
    content = Column(Text)
    author = Column(String(50))

实现 CRUD 接口

使用 FastAPI 实现 CRUD 操作:

@app.get("/api/posts")
def list_posts(): ...

@app.post("/api/posts")
def create_post(post: PostCreate): ...

@app.get("/api/posts/{id}")
def get_post(id: int): ...

@app.put("/api/posts/{id}")
def update_post(id: int, post: PostUpdate): ...

@app.delete("/api/posts/{id}")
def delete_post(id: int): ...

API 设计最佳实践

  • URL 使用名词复数:/api/posts 而不是 /api/get_post
  • 版本控制:/api/v1/posts
  • 分页:/api/posts?page=1&size=10
  • 过滤和排序:/api/posts?sort=-created_at
  • 统一错误格式:{ “error”: { “code”: “…”, “message”: “…” } }
  • 合理使用状态码:200/201/204/400/404/500

测试

FastAPI 自带交互式 API 文档,启动服务后访问 /docs 即可看到 Swagger UI,可以直接在浏览器中测试所有接口。

也可以用 pytest 编写自动化测试:

from fastapi.testclient import TestClient

def test_create_post():
    response = client.post("/api/posts", json={...})
    assert response.status_code == 201

总结

构建 RESTful API 的关键在于理解 REST 的设计原则,并选择合适的工具。FastAPI 结合了高性能和开发便利性,是构建现代 API 的优秀选择。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注