0Pricing
FastAPI Backend Development Bootcamp · 课时

使用 FastAPI 实现 API 网关

学习使用 FastAPI 构建 API 网关,将请求路由到多个微服务并汇总响应。

使用 FastAPI 实现 API 网关 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What's an API Gateway?

Imagine your microservices are different shops in a mall. An API Gateway is like the mall's main entrance or information desk.

  • It's a single entry point for all client requests.
  • It routes requests to the correct backend service.
  • It can combine responses from multiple services.
  • It handles shared tasks like authentication or logging.

This keeps your client apps simpler and your backend services focused.

Why FastAPI for a Gateway?

FastAPI is an excellent choice for building an API Gateway due to its modern features:

  • Asynchronous nature: It can handle many requests concurrently without blocking, perfect for proxying.
  • High performance: Built on Starlette and Pydantic, it's very fast.
  • Easy routing: FastAPI's intuitive routing makes directing requests simple.
  • Dependency Injection: Helps manage shared resources and logic efficiently.

It acts as a lightweight, powerful reverse proxy.

The Core Idea: Proxying Requests

The main job of an API Gateway is to act as a proxy. This means it receives a request from a client, forwards it to a backend service, and then sends the backend's response back to the client.

We'll use the httpx library in Python to make asynchronous HTTP requests to our backend services from within our FastAPI gateway.

First, make sure you have httpx installed: pip install httpx

Basic GET Request Proxy

Let's create a simple FastAPI gateway that proxies a GET request to a public dummy API. Our gateway endpoint /proxy-todo will fetch a todo item from jsonplaceholder.typicode.com.

import httpx
from fastapi import FastAPI
import uvicorn

app = FastAPI()
BACKEND_SERVICE_URL = "https://jsonplaceholder.typicode.com/todos/1"

@app.get("/proxy-todo")
async def proxy_todo_item():
    async with httpx.AsyncClient() as client:
        response = await client.get(BACKEND_SERVICE_URL)
        response.raise_for_status() # Raises HTTPStatusError for 4xx/5xx responses
        return response.json()

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Forwarding Path Parameters

Often, backend services require dynamic data in their URLs, known as path parameters. Your API Gateway needs to capture these parameters from the client request and forward them to the correct backend URL.

Here, we proxy requests to /proxy-todos/{todo_id}, passing todo_id to the backend.

import httpx
from fastapi import FastAPI
import uvicorn

app = FastAPI()
BACKEND_BASE_URL = "https://jsonplaceholder.typicode.com"

@app.get("/proxy-todos/{todo_id}")
async def proxy_todo_item_by_id(todo_id: int):
    async with httpx.AsyncClient() as client:
        backend_url = f"{BACKEND_BASE_URL}/todos/{todo_id}"
        response = await client.get(backend_url)
        response.raise_for_status()
        return response.json()

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Handling POST/PUT Request Bodies

For requests like POST or PUT, clients send data in the request body. Your API Gateway must receive this body and forward it to the backend service. FastAPI's Request object allows us to access the raw request body.

We'll use request.json() to get the JSON body and pass it to httpx.

import httpx
from fastapi import FastAPI, Request
import uvicorn

app = FastAPI()
BACKEND_POST_URL = "https://jsonplaceholder.typicode.com/posts"

@app.post("/proxy-post")
async def proxy_create_post(request: Request):
    body = await request.json() # Get the raw JSON body from the client
    async with httpx.AsyncClient() as client:
        # Forward the body to the backend service
        response = await client.post(BACKEND_POST_URL, json=body)
        response.raise_for_status()
        return response.json()

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Aggregating Multiple Responses

One powerful feature of an API Gateway is response aggregation. This means the gateway can call multiple backend services, combine their individual responses, and return a single, unified response to the client.

This reduces the number of requests a client needs to make, simplifying client-side logic and potentially improving performance.

Example: User & Order Aggregation

Let's see an example where our gateway fetches user details from one backend and then a list of todos for that user from another, combining them into a single response.

import httpx
from fastapi import FastAPI
import uvicorn

app = FastAPI()
BACKEND_USERS_URL = "https://jsonplaceholder.typicode.com/users"
BACKEND_TODOS_URL = "https://jsonplaceholder.typicode.com/todos"

@app.get("/user-with-todos/{user_id}")
async def get_user_with_todos(user_id: int):
    async with httpx.AsyncClient() as client:
        # Fetch user details
        user_response = await client.get(f"{BACKEND_USERS_URL}/{user_id}")
        user_response.raise_for_status()
        user_data = user_response.json()

        # Fetch todos for that user
        todos_response = await client.get(f"{BACKEND_TODOS_URL}?userId={user_id}")
        todos_response.raise_for_status()
        todos_data = todos_response.json()

        # Combine the data before returning
        user_data["todos"] = todos_data
        return user_data

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Cross-Cutting Concerns at Gateway

Besides routing and aggregation, API Gateways are perfect for handling cross-cutting concerns. These are features needed by many services but not central to any one service's business logic.

  • Authentication & Authorization: Validate tokens once at the gateway.
  • Logging & Monitoring: Centralized request logging.
  • Rate Limiting: Protect backend services from overload.
  • Caching: Cache common responses to speed up delivery.

This offloads work from individual microservices.

Gateway Benefits Check

Which of the following are key benefits of using an API Gateway in a microservices architecture?

API Gateway with FastAPI Recap

You've learned how to build a powerful API Gateway using FastAPI!

  • We understood what an API Gateway is and its benefits.
  • We leveraged FastAPI's async capabilities for efficient proxying.
  • We implemented basic GET, path parameter, and POST body forwarding.
  • We explored how to aggregate responses from multiple backend services.
  • You also saw how gateways centralize cross-cutting concerns.

FastAPI provides a robust and performant foundation for your microservice entry point!

常见问题解答

「使用 FastAPI 实现 API 网关」课时是免费的吗?

是的 — 「使用 FastAPI 实现 API 网关」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「使用 FastAPI 实现 API 网关」这节课中我会学到什么?

学习使用 FastAPI 构建 API 网关,将请求路由到多个微服务并汇总响应。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 FastAPI 实现 API 网关」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设计微服务架构
  2. 服务间通信
  3. 使用 FastAPI 实现 API 网关
  4. 服务发现与健康检查
← 返回 FastAPI Backend Development Bootcamp