FastAPI
FastAPI is a modern, fast (high-performance) Web framework for building APIs with Python, based on standard Python type hints. Key features include:
- Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic)
- Efficient Coding: Increases the speed of feature development by approximately 200% to 300%
- Fewer bugs: Reduces approximately 40% of human (developer) induced errors
- Intelligent: Great editor support with completion everywhere, reducing debugging time
- Simple: Designed to be easy to use and learn, requiring less time reading documentation
- Automatic Documentation: Automatically generates interactive API documentation
This guide describes how to deploy FastAPI applications on CloudBase HTTP cloud functions.
Prerequisites
Before you begin, ensure that you have:
- Installed Python 3.10 or a later version
- Have a Tencent Cloud account and have activated the CloudBase service
- Have a basic knowledge of Python and FastAPI development
Step 1: Create a FastAPI Project
💡 Note: If you already have a FastAPI project, you can skip this step.
Create the project directory
mkdir fastapi-cloudbase
cd fastapi-cloudbase
Create application files
Create the app.py file, which is the entry file of the application:
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from typing import List, Optional
import uvicorn
app = FastAPI(
title="FastAPI CloudBase Demo",
description="A FastAPI application running on CloudBase HTTP Functions",
version="1.0.0"
)
# Data Model
class User(BaseModel):
id: int
name: str
email: str
age: Optional[int] = None
class UserCreate(BaseModel):
name: str
email: str
age: Optional[int] = None
# Mock Database
users_db = [
User(id=1, name="Zhang San", email="zhangsan@example.com", age=25),
User(id=2, name="Li Si", email="lisi@example.com", age=30),
User(id=3, name="Wang Wu", email="wangwu@example.com", age=28)
]
@app.get("/")
async def root():
"""Root path handler function"""
return {
"message": "Hello from FastAPI on CloudBase!",
"framework": "FastAPI",
"docs": "/docs",
"redoc": "/redoc"
}
@app.get("/health")
async def health_check():
"""Health Check Endpoint"""
return {
"status": "healthy",
"framework": "FastAPI",
"version": "1.0.0"
}
@app.get("/api/users", response_model=List[User])
async def get_users(
page: int = Query(1, ge=1, description="Page number"),
limit: int = Query(10, ge=1, le=100, description="Items per page")
):
"""Obtain user list (supports pagination)"""
start_index = (page - 1) * limit
end_index = start_index + limit
paginated_users = users_db[start_index:end_index]
return paginated_users
@app.get("/api/users/{user_id}", response_model=User)
async def get_user(user_id: int):
"""Obtain user by ID"""
user = next((user for user in users_db if user.id == user_id), None)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.post("/api/users", response_model=User, status_code=201)
async def create_user(user: UserCreate):
"""Create New User"""
# Checking whether the email already exists
if any(u.email == user.email for u in users_db):
raise HTTPException(status_code=400, detail="Email already registered")
# Generate New ID
new_id = max(u.id for u in users_db) + 1 if users_db else 1
# Create New User
new_user = User(id=new_id, **user.dict())
users_db.append(new_user)
return new_user
@app.put("/api/users/{user_id}", response_model=User)
async def update_user(user_id: int, user_update: UserCreate):
"""Update User Information"""
user_index = next((i for i, u in enumerate(users_db) if u.id == user_id), None)
if user_index is None:
raise HTTPException(status_code=404, detail="User not found")
# Check whether the email is already in use by another user
if any(u.email == user_update.email and u.id != user_id for u in users_db):
raise HTTPException(status_code=400, detail="Email already registered")
# Update User
updated_user = User(id=user_id, **user_update.dict())
users_db[user_index] = updated_user
return updated_user
@app.delete("/api/users/{user_id}")
async def delete_user(user_id: int):
"""Delete User"""
user_index = next((i for i, u in enumerate(users_db) if u.id == user_id), None)
if user_index is None:
raise HTTPException(status_code=404, detail="User not found")
deleted_user = users_db.pop(user_index)
return {"message": f"User {deleted_user.name} deleted successfully"}
# Custom Exception Handling
@app.exception_handler(404)
async def not_found_handler(request, exc):
return {"error": "Not Found", "message": "The requested resource was not found"}
@app.exception_handler(500)
async def internal_error_handler(request, exc):
return {"error": "Internal Server Error", "message": "Something went wrong"}
if __name__ == "__main__":
# CloudBase HTTP cloud function requires listening on port 9000
uvicorn.run(app, host="0.0.0.0", port=9000)
Create dependency file
Create the requirements.txt file:
fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic==1.10.2
💡 Note:
fastapi: FastAPI frameworkuvicorn: ASGI server for running FastAPI applicationspydantic: Data validation and serialization library, use version 1.x to avoid pydantic_core dependency