### Project Setup and Server Start with UV Source: https://jiayuxu0.github.io/FastAPI-Template/index This snippet outlines the steps to clone the project, install dependencies using UV, initialize the database with Aerich, and start the development server using Uvicorn. It's essential for setting up the development environment. ```bash # 克隆项目 git clone https://github.com/JiayuXu0/FastAPI-Template.git cd FastAPI-Template # 安装依赖 curl -LsSf https://astral.sh/uv/install.sh | sh uv sync # 初始化数据库 uv run aerich init-db # 启动开发服务器 uv run uvicorn src:app --reload --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Get Role - Python (requests) Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Provides an example of retrieving a role using the Python requests library. Demonstrates setting headers and query parameters for authentication. ```python import requests headers = { "Authorization": "Bearer <your-token>" } params = {} response = requests.get( "http://localhost:8000/api/v1/role/get", headers=headers, params=params ) print(response.json()) ``` -------------------------------- ### Fix dependency installation errors with uv Source: https://jiayuxu0.github.io/FastAPI-Template/faq Provide shell commands to clean the uv cache and reinstall dependencies. Ensure Python 3.11+ is used and network connectivity is fine. This resolves package conflicts during installation. ```shell # 清理缓存 uv cache clean # 重新安装 uv sync --reinstall ``` -------------------------------- ### List Users API - cURL Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Example of how to list users using cURL. It sends a GET request to the /api/v1/users/list endpoint with an Authorization header. No request body is required. ```bash curl -X GET "http://localhost:8000/api/v1/users/list" \ -H "Authorization: Bearer " ``` -------------------------------- ### View Role Permissions API Example (cURL, Python) Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Shows how to retrieve the permissions associated with a specific role. This is a GET request to the /api/v1/role/authorized endpoint and requires an authorization token. The examples include both cURL and Python using the 'requests' library. The API supports an optional 'id' query parameter for the role ID. ```curl curl -X GET "http://localhost:8000/api/v1/role/authorized" \ -H "Authorization: Bearer " ``` ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/role/authorized", headers=headers, params=params ) print(response.json()) ``` -------------------------------- ### 查看 API 列表 (GET /api/v1/api/list) Source: https://jiayuxu0.github.io/FastAPI-Template/api/api 获取 API 列表的接口,支持分页、按路径、简介和标签过滤。返回包含状态码、消息和数据的 JSON 对象。 ```curl curl -X GET "http://localhost:8000/api/v1/api/list" \ -H "Authorization: Bearer " ``` ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/api/list", headers=headers, params=params ) print(response.json()) ``` -------------------------------- ### Create User API - cURL Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Example of how to create a new user using cURL. This involves a POST request to /api/v1/users/create with JSON payload containing user details like email, username, and password. ```bash curl -X POST "http://localhost:8000/api/v1/users/create" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"email": "admin@example.com", "username": "admin", "password": "password123"}' ``` -------------------------------- ### Dependency Inversion Example (Python) Source: https://jiayuxu0.github.io/FastAPI-Template/architecture Demonstrates the Dependency Inversion Principle where the Service layer depends on an abstract Repository. This allows for easier testing and swapping of data access implementations. ```python class UserService: def __init__(self, user_repo: UserRepository): self.user_repo = user_repo ``` -------------------------------- ### List Users API - Python (requests) Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Python example using the requests library to list users. It makes a GET request to the /api/v1/users/list endpoint, including an Authorization header. Query parameters can be passed in the 'params' dictionary. ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/users/list", headers=headers, params=params ) print(response.json()) ``` -------------------------------- ### Add new database table using Aerich Source: https://jiayuxu0.github.io/FastAPI-Template/faq Generate and apply migrations for new models defined in src/models/. Run migrate to create migration file, then upgrade to apply it. Requires Aerich ORM setup. ```shell # 生成迁移 uv run aerich migrate --name "add_new_table" # 应用迁移 uv run aerich upgrade ``` -------------------------------- ### Get User API - Python (requests) Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Python example using the requests library to get user details. It performs a GET request to the /api/v1/users/get endpoint with an Authorization header. The 'params' dictionary can be used for query parameters such as 'user_id'. ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/users/get", headers=headers, params=params ) print(response.json()) ``` -------------------------------- ### Run tests using pytest in FastAPI project Source: https://jiayuxu0.github.io/FastAPI-Template/faq Use uv run pytest to execute tests. Options include running all tests, specific files, or with coverage report. Requires pytest installed. ```shell # 运行所有测试 uv run pytest # 运行特定测试文件 uv run pytest tests/test_users.py # 运行带覆盖率的测试 uv run pytest --cov=src --cov-report=html ``` -------------------------------- ### Get User API - cURL Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Example of how to retrieve a specific user's details using cURL. It sends a GET request to the /api/v1/users/get endpoint with an Authorization header. Query parameters like 'user_id' can be included. ```bash curl -X GET "http://localhost:8000/api/v1/users/get" \ -H "Authorization: Bearer " ``` -------------------------------- ### Dependency Injection Example (Python) Source: https://jiayuxu0.github.io/FastAPI-Template/architecture Demonstrates FastAPI's dependency injection system. A `get_user_service` function provides an instance of `UserService`, which is then injected into the API endpoint, promoting loose coupling and testability. ```python # 依赖定义 def get_user_service() -> UserService: return UserService(user_repository) # 使用依赖 @router.post("/users") async def create_user( user_data: UserCreate, user_service: UserService = Depends(get_user_service) ): return await user_service.create_user(user_data) ``` -------------------------------- ### Create User API - Python (requests) Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Python example for creating a user using the requests library. It sends a POST request to /api/v1/users/create, including an Authorization header and a JSON body with user credentials. ```python import requests headers = { "Authorization": "Bearer " } data = { "email": "admin@example.com", "username": "admin", "password": "password123", } response = requests.post( "http://localhost:8000/api/v1/users/create", headers=headers, json=data ) print(response.json()) ``` -------------------------------- ### Custom HTTP Middleware Example (Python) Source: https://jiayuxu0.github.io/FastAPI-Template/architecture Provides an example of implementing custom HTTP middleware in FastAPI. The middleware can process requests before they reach the route handler and responses after they are generated. ```python @app.middleware("http") async def custom_middleware(request: Request, call_next): # 处理请求前 response = await call_next(request) # 处理响应后 return response ``` -------------------------------- ### 查看 API (GET /api/v1/api/get) Source: https://jiayuxu0.github.io/FastAPI-Template/api/api 根据 ID 获取单个 API 详细信息的接口。返回包含状态码、消息和数据的 JSON 对象。 ```curl curl -X GET "http://localhost:8000/api/v1/api/get" \ -H "Authorization: Bearer " ``` ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/api/get", headers=headers, params=params ) print(response.json()) ``` -------------------------------- ### Add New Feature: Product Model (Python) Source: https://jiayuxu0.github.io/FastAPI-Template/architecture Example of adding a new feature module by defining a `Product` model in the `src/models/` directory. This demonstrates how to extend the application's data structure. ```python class Product(BaseModel, TimestampMixin): name = fields.CharField(max_length=100) price = fields.DecimalField(max_digits=10, decimal_places=2) ``` -------------------------------- ### Delete Role API Example (cURL, Python) Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Demonstrates how to delete a role using the API. Requires an authorization token. The cURL example shows a direct command-line request, while the Python example uses the 'requests' library for programmatic interaction. Both send a DELETE request to the /api/v1/role/delete endpoint. ```curl curl -X DELETE "http://localhost:8000/api/v1/role/delete" \ -H "Authorization: Bearer " ``` ```python import requests headers = { "Authorization": "Bearer " } response = requests.delete( "http://localhost:8000/api/v1/role/delete", headers=headers ) print(response.json()) ``` -------------------------------- ### Open/Closed Principle Extension Example (Python) Source: https://jiayuxu0.github.io/FastAPI-Template/architecture Illustrates the Open/Closed Principle by extending an existing UserService with new functionality (sending notifications) without modifying the original class. This promotes extensibility. ```python # 通过继承扩展功能 class EnhancedUserService(UserService): def create_user_with_notification(self, user_data): user = super().create_user(user_data) self.send_notification(user) return user ``` -------------------------------- ### GET /api/v1/api/list Source: https://jiayuxu0.github.io/FastAPI-Template/api/api Retrieves a list of APIs with optional filtering by path, summary, or tags. ```APIDOC ## GET /api/v1/api/list ### Description Retrieves a list of APIs with optional filtering. ### Method GET ### Endpoint /api/v1/api/list #### Query Parameters - **page** (int) - Optional - The page number. Defaults to 1. - **page_size** (int) - Optional - The number of items per page. Defaults to 10. - **path** (str) - Optional - Filters APIs by their path. - **summary** (str) - Optional - Filters APIs by their summary. - **tags** (str) - Optional - Filters APIs by their tags. ### Response #### Success Response (200) - **code** (int) - The response code, expected to be 200 for success. - **msg** (str) - A message indicating the status of the operation, e.g., "success". - **data** (...) - The data payload containing the list of APIs. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (int) - The error code (e.g., 400, 401, 403, 404, 500). - **msg** (str) - An error message describing the issue. - **data** (null) - Typically null for error responses. #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ### Request Example **cURL** : ``` curl -X GET "http://localhost:8000/api/v1/api/list" \ -H "Authorization: Bearer " ``` **Python (requests)** : ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/api/list", headers=headers, params=params ) print(response.json()) ``` ``` -------------------------------- ### Reset database and migrations for FastAPI Source: https://jiayuxu0.github.io/FastAPI-Template/faq Remove the SQLite database file and migrations directory, then reinitialize the database. This is for SQLite only. Useful for starting over with the database. ```shell # SQLite rm fastapi_template.db # 删除迁移记录 rm -rf migrations/ # 重新初始化 uv run aerich init-db ``` -------------------------------- ### Update Role Permissions API Example (cURL, Python) Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Provides examples for updating role permissions. This involves a POST request to the /api/v1/role/authorized endpoint with a JSON payload containing the role ID and optionally menu and API IDs. Both cURL and Python (using 'requests') are demonstrated, including setting the 'Authorization' and 'Content-Type' headers. ```curl curl -X POST "http://localhost:8000/api/v1/role/authorized" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"id": 1}' ``` ```python import requests headers = { "Authorization": "Bearer " } data = { "id": 1, } response = requests.post( "http://localhost:8000/api/v1/role/authorized", headers=headers, json=data ) print(response.json()) ``` -------------------------------- ### GET /api/v1/base/version Source: https://jiayuxu0.github.io/FastAPI-Template/api/base Retrieves the current API version information. ```APIDOC ## GET /api/v1/base/version ### Description Retrieves the current API version information. ### Method GET ### Endpoint /api/v1/base/version ### Response #### Success Response (200) - **code** (integer) - Response status code - **msg** (string) - Success message - **data** (any) - API response data containing version details #### Response Example ```json { "code": 200, "msg": "success", "data": "..." } ``` #### Error Response - **code** (integer) - Error status code (e.g., 400, 401, 403, 404, 500) - **msg** (string) - Error message - **data** (null) #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ``` -------------------------------- ### GET /api/v1/api/get Source: https://jiayuxu0.github.io/FastAPI-Template/api/api Retrieves details of a specific API by its ID. ```APIDOC ## GET /api/v1/api/get ### Description Retrieves details for a specific API using its ID. ### Method GET ### Endpoint /api/v1/api/get #### Query Parameters - **id** (int) - Optional - The ID of the API to retrieve. If not provided, the behavior might be undefined or return a default. ### Response #### Success Response (200) - **code** (int) - The response code, expected to be 200 for success. - **msg** (str) - A message indicating the status of the operation, e.g., "success". - **data** (...) - The data payload containing the API details. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (int) - The error code (e.g., 400, 401, 403, 404, 500). - **msg** (str) - An error message describing the issue. - **data** (null) - Typically null for error responses. #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ### Request Example **cURL** : ``` curl -X GET "http://localhost:8000/api/v1/api/get" \ -H "Authorization: Bearer " ``` **Python (requests)** : ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/api/get", headers=headers, params=params ) print(response.json()) ``` ``` -------------------------------- ### API Response Format Examples - JSON Source: https://jiayuxu0.github.io/FastAPI-Template/api/api Defines the standard JSON structure for successful and error responses across endpoints. Success includes a 200 code with message and data; errors use 4xx/5xx codes with message and null data. No dependencies beyond HTTP client; outputs are JSON objects. ```JSON { "code": 200, "msg": "success", "data": ... } ``` ```JSON { "code": 400, "msg": "错误信息", "data": null } ``` -------------------------------- ### GET /api/v1/base/userinfo Source: https://jiayuxu0.github.io/FastAPI-Template/api/base Retrieves information about the currently authenticated user. ```APIDOC ## GET /api/v1/base/userinfo ### Description Retrieves information about the currently authenticated user. ### Method GET ### Endpoint /api/v1/base/userinfo ### Parameters #### Query Parameters - **current_user** (models.admin.User) - Optional - Represents the current user, typically determined by authentication. ### Response #### Success Response (200) - **code** (integer) - Response status code - **msg** (string) - Success message - **data** (any) - API response data containing user information #### Response Example ```json { "code": 200, "msg": "success", "data": "..." } ``` #### Error Response - **code** (integer) - Error status code (e.g., 400, 401, 403, 404, 500) - **msg** (string) - Error message - **data** (null) #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ``` -------------------------------- ### GET /api/v1/role/list Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Retrieves a list of roles with optional filtering and pagination. ```APIDOC ## GET /api/v1/role/list ### Description Retrieves a paginated list of roles. Supports filtering by role name. ### Method GET ### Endpoint /api/v1/role/list #### Query Parameters - **page** (integer) - Optional - The page number. Defaults to 1. - **page_size** (integer) - Optional - The number of items per page. Defaults to 10. - **role_name** (string) - Optional - The name of the role to filter by. ### Response #### Success Response (200) - **code** (integer) - The status code, indicating success. - **msg** (string) - A message indicating the result of the operation. - **data** (...) - The list of roles matching the query. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (integer) - The status code, indicating an error (e.g., 400, 401, 403, 404, 500). - **msg** (string) - A message describing the error. - **data** (null) - Null value for error responses. #### Error Response Example ```json { "code": 400, "msg": "错误信息", "data": null } ``` ### Usage Example (cURL) ```bash curl -X GET "http://localhost:8000/api/v1/role/list" \ -H "Authorization: Bearer " ``` ### Usage Example (Python requests) ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/role/list", headers=headers, params=params ) print(response.json()) ``` ``` -------------------------------- ### GET /api/v1/base/health Source: https://jiayuxu0.github.io/FastAPI-Template/api/base Performs a health check on the system to ensure it is operational. ```APIDOC ## GET /api/v1/base/health ### Description Performs a health check on the system to ensure it is operational. ### Method GET ### Endpoint /api/v1/base/health ### Response #### Success Response (200) - **code** (integer) - Response status code - **msg** (string) - Success message - **data** (any) - API response data, typically indicating system health #### Response Example ```json { "code": 200, "msg": "success", "data": "..." } ``` #### Error Response - **code** (integer) - Error status code (e.g., 400, 401, 403, 404, 500) - **msg** (string) - Error message - **data** (null) #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ``` -------------------------------- ### GET /api/v1/users/list Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Retrieves a list of users with optional filtering and pagination. Allows searching by username and email, and filtering by department ID. ```APIDOC ## GET /api/v1/users/list ### Description Retrieves a list of users with optional filtering and pagination. Allows searching by username and email, and filtering by department ID. ### Method GET ### Endpoint /api/v1/users/list ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number. Defaults to 1. - **page_size** (integer) - Optional - The number of items per page. Defaults to 10. - **username** (string) - Optional - Filter users by username. - **email** (string) - Optional - Filter users by email address. - **dept_id** (integer) - Optional - Filter users by department ID. ### Response #### Success Response (200) - **code** (integer) - The status code, expected to be 200 for success. - **msg** (string) - A message indicating the outcome, typically 'success'. - **data** (...) - The payload containing the list of users. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (integer) - The status code, which can be 400, 401, 403, 404, or 500. - **msg** (string) - A message describing the error. - **data** (null) - Null for error responses. #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ### Usage Example (cURL) ```bash curl -X GET "http://localhost:8000/api/v1/users/list" \ -H "Authorization: Bearer " ``` ### Usage Example (Python) ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/users/list", headers=headers, params=params ) print(response.json()) ``` ``` -------------------------------- ### Update Role - Python (requests) Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Provides an example of updating a role using the Python requests library with a JSON payload. Demonstrates sending data as JSON. ```python import requests headers = { "Authorization": "Bearer <your-token>" } data = { "id": 1, "name": "admin", } response = requests.post( "http://localhost:8000/api/v1/role/update", headers=headers, json=data ) print(response.json()) ``` -------------------------------- ### GET /api/v1/users/get Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Retrieves details for a specific user based on their user ID. ```APIDOC ## GET /api/v1/users/get ### Description Retrieves details for a specific user based on their user ID. ### Method GET ### Endpoint /api/v1/users/get ### Parameters #### Query Parameters - **user_id** (integer) - Optional - The ID of the user to retrieve. ### Response #### Success Response (200) - **code** (integer) - The status code, expected to be 200 for success. - **msg** (string) - A message indicating the outcome, typically 'success'. - **data** (...) - The payload containing the user's details. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (integer) - The status code, which can be 400, 401, 403, 404, or 500. - **msg** (string) - A message describing the error. - **data** (null) - Null for error responses. #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ### Usage Example (cURL) ```bash curl -X GET "http://localhost:8000/api/v1/users/get" \ -H "Authorization: Bearer " ``` ### Usage Example (Python) ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/users/get", headers=headers, params=params ) print(response.json()) ``` ``` -------------------------------- ### Get Role - cURL Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Illustrates retrieving a specific role using a cURL request with the role ID as a query parameter. Authentication is required. ```bash curl -X GET "http://localhost:8000/api/v1/role/get" -H "Authorization: Bearer " ``` -------------------------------- ### Update User API - Python (requests) Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Python example using the requests library to update user information. It sends a POST request to /api/v1/users/update with an Authorization header and a JSON payload containing the user ID and updated fields. ```python import requests headers = { "Authorization": "Bearer " } data = { "id": 1, "email": "admin@example.com", "username": "admin" } response = requests.post( "http://localhost:8000/api/v1/users/update", headers=headers, json=data ) print(response.json()) ``` -------------------------------- ### Update User API - cURL Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Example of how to update an existing user using cURL. This POST request to /api/v1/users/update requires a JSON body with the user's ID and the fields to be updated, along with an Authorization header. ```bash curl -X POST "http://localhost:8000/api/v1/users/update" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"id": 1, "email": "admin@example.com", "username": "admin"}' ``` -------------------------------- ### Optimize Database Queries in Python ORM Source: https://jiayuxu0.github.io/FastAPI-Template/faq This code shows techniques to optimize database queries using select_related and prefetch_related for preloading associated data in an ORM like Tortoise ORM or Django. It requires an ORM setup with User model and related roles/permissions. Inputs are query objects, outputs are optimized user lists; it improves performance by reducing N+1 queries but may increase memory usage for large datasets. ```python # 预加载关联数据 users = await User.all().select_related("roles") # 批量预加载 users = await User.all().prefetch_related("roles__permissions") ``` -------------------------------- ### Add New Feature: Product Repository (Python) Source: https://jiayuxu0.github.io/FastAPI-Template/architecture Shows how to create a `ProductRepository` by inheriting from `BaseRepository`. This follows the Repository pattern for managing product data access. ```python class ProductRepository(BaseRepository): def __init__(self): super().__init__(Product) ``` -------------------------------- ### POST /api/v1/api/create Source: https://jiayuxu0.github.io/FastAPI-Template/api/api Creates a new API entry. ```APIDOC ## POST /api/v1/api/create ### Description Creates a new API entry with the provided details. ### Method POST ### Endpoint /api/v1/api/create #### Request Body - **path** (str) - Required - The path of the API. - **summary** (str) - Optional - A brief summary of the API. - **method** (enum 'MethodType') - Required - The HTTP method of the API. - **tags** (str) - Required - The tags associated with the API. ### Request Example ```json { "path": "/api/v1/example", "method": null, "tags": "示例模块" } ``` ### Response #### Success Response (200) - **code** (int) - The response code, expected to be 200 for success. - **msg** (str) - A message indicating the status of the operation, e.g., "success". - **data** (...) - The data payload, potentially containing the created API details. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (int) - The error code (e.g., 400, 401, 403, 404, 500). - **msg** (str) - An error message describing the issue. - **data** (null) - Typically null for error responses. #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ### Request Example **cURL** : ``` curl -X POST "http://localhost:8000/api/v1/api/create" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"path": "/api/v1/example", "method": "value", "tags": "示例模块"}' ``` **Python (requests)** : ```python import requests headers = { "Authorization": "Bearer " } data = { "path": "/api/v1/example", "method": "value", "tags": "示例模块", } response = requests.post( "http://localhost:8000/api/v1/api/create", headers=headers, json=data ) print(response.json()) ``` ``` -------------------------------- ### POST /api/v1/users/create Source: https://jiayuxu0.github.io/FastAPI-Template/api/users Creates a new user with the provided details. Requires email, username, and password. ```APIDOC ## POST /api/v1/users/create ### Description Creates a new user with the provided details. Requires email, username, and password. ### Method POST ### Endpoint /api/v1/users/create ### Parameters #### Request Body - **email** (EmailStr) - Required - The email address of the user. - **username** (string) - Required - The username for the new user (3-20 alphanumeric characters and underscores). - **password** (string) - Required - The user's password (at least 8 characters, containing letters and numbers). - **is_active** (boolean) - Optional - Whether the user account is active. - **is_superuser** (boolean) - Optional - Whether the user has superuser privileges. - **role_ids** (list[integer]) - Optional - A list of role IDs assigned to the user. - **dept_id** (integer) - Optional - The ID of the department the user belongs to. ### Request Example ```json { "email": "admin@example.com", "username": "admin", "password": "password123" } ``` ### Response #### Success Response (200) - **code** (integer) - The status code, expected to be 200 for success. - **msg** (string) - A message indicating the outcome, typically 'success'. - **data** (...) - The payload containing the newly created user's details. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (integer) - The status code, which can be 400, 401, 403, 404, or 500. - **msg** (string) - A message describing the error. - **data** (null) - Null for error responses. #### Error Response Example ```json { "code": 400, "msg": "Error message", "data": null } ``` ### Usage Example (cURL) ```bash curl -X POST "http://localhost:8000/api/v1/users/create" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"email": "admin@example.com", "username": "admin", "password": "password123"}' ``` ### Usage Example (Python) ```python import requests headers = { "Authorization": "Bearer " } data = { "email": "admin@example.com", "username": "admin", "password": "password123", } response = requests.post( "http://localhost:8000/api/v1/users/create", headers=headers, json=data ) print(response.json()) ``` ``` -------------------------------- ### Enable debug logging for FastAPI app Source: https://jiayuxu0.github.io/FastAPI-Template/faq Run uvicorn with debug log level to see detailed startup logs. Useful for troubleshooting errors. Set in .env for persistent debug mode. ```shell # 查看详细日志 uv run uvicorn src:app --reload --log-level debug ``` -------------------------------- ### Deploy FastAPI app using Docker Source: https://jiayuxu0.github.io/FastAPI-Template/faq Build a Docker image for the app and run it as a container. Expose port 8000. Use -d for detached mode. Requires Dockerfile in project. ```shell # 构建镜像 docker build -t fastapi-template . # 运行容器 docker run -d -p 8000:8000 --name fastapi-app fastapi-template ``` -------------------------------- ### 创建 API (POST /api/v1/api/create) Source: https://jiayuxu0.github.io/FastAPI-Template/api/api 创建新的 API 记录。需要提供 API 路径、方法和标签等信息。支持 JSON 请求体,并返回操作结果。 ```curl curl -X POST "http://localhost:8000/api/v1/api/create" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"path": "/api/v1/example", "method": "value", "tags": "示例模块"}' ``` ```python import requests headers = { "Authorization": "Bearer " } data = { "path": "/api/v1/example", "method": "value", "tags": "示例模块", } response = requests.post( "http://localhost:8000/api/v1/api/create", headers=headers, json=data ) print(response.json()) ``` -------------------------------- ### Add New Feature: Product Service (Python) Source: https://jiayuxu0.github.io/FastAPI-Template/architecture Demonstrates creating a `ProductService` that utilizes the `ProductRepository`. This follows the Service layer pattern for encapsulating product-related business logic. ```python class ProductService(BaseService): def __init__(self, product_repo: ProductRepository): super().__init__(product_repo) ``` -------------------------------- ### GET /api/v1/role/get Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Retrieves details of a specific role by its ID. ```APIDOC ## GET /api/v1/role/get ### Description Retrieves the details of a specific role using its unique identifier. ### Method GET ### Endpoint /api/v1/role/get #### Query Parameters - **role_id** (integer) - Optional - The ID of the role to retrieve. ### Response #### Success Response (200) - **code** (integer) - The status code, indicating success. - **msg** (string) - A message indicating the result of the operation. - **data** (...) - The role details. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (integer) - The status code, indicating an error (e.g., 400, 401, 403, 404, 500). - **msg** (string) - A message describing the error. - **data** (null) - Null value for error responses. #### Error Response Example ```json { "code": 400, "msg": "错误信息", "data": null } ``` ### Usage Example (cURL) ```bash curl -X GET "http://localhost:8000/api/v1/role/get" \ -H "Authorization: Bearer " ``` ### Usage Example (Python requests) ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/role/get", headers=headers, params=params ) print(response.json()) ``` ``` -------------------------------- ### Set production environment variables for FastAPI Source: https://jiayuxu0.github.io/FastAPI-Template/faq Export environment variables for production deployment. Includes secret key, database host, and password. Avoid using .env in production. ```shell export SECRET_KEY="your-secret-key" export DB_HOST="your-db-host" export DB_PASSWORD="your-db-password" ``` -------------------------------- ### Create Role - Python (requests) Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Shows how to create a new role using the Python requests library with a JSON payload. Demonstrates setting headers and sending data as JSON. ```python import requests headers = { "Authorization": "Bearer <your-token>" } data = { "name": "admin", } response = requests.post( "http://localhost:8000/api/v1/role/create", headers=headers, json=data ) print(response.json()) ``` -------------------------------- ### List Roles - Python (requests) Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Shows how to list roles using the Python requests library. Includes setting headers and query parameters for authentication and optional filtering. ```python import requests headers = { "Authorization": "Bearer <your-token>" } params = {} response = requests.get( "http://localhost:8000/api/v1/role/list", headers=headers, params=params ) print(response.json()) ``` -------------------------------- ### GET /api/v1/role/authorized Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Retrieves the permissions for a specific role. The role ID can be provided as a query parameter. ```APIDOC ## GET /api/v1/role/authorized ### Description Retrieves the permissions for a specific role. The role ID can be provided as a query parameter. ### Method GET ### Endpoint /api/v1/role/authorized ### Parameters #### Path Parameters None #### Query Parameters - **id** (integer) - Optional - The ID of the role to retrieve permissions for. #### Request Body None ### Request Example **cURL**: ``` curl -X GET "http://localhost:8000/api/v1/role/authorized" \ -H "Authorization: Bearer " ``` **Python (requests)**: ```python import requests headers = { "Authorization": "Bearer " } params = { } response = requests.get( "http://localhost:8000/api/v1/role/authorized", headers=headers, params=params ) print(response.json()) ``` ### Response #### Success Response (200) - **code** (integer) - Indicates success. - **msg** (string) - Success message. - **data** (any) - Data containing role permissions. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response (400, 401, 403, 404, 500) - **code** (integer) - Error code. - **msg** (string) - Error message. - **data** (null) - Null value for error data. ``` -------------------------------- ### POST /api/v1/role/create Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Creates a new role with the specified name and description. ```APIDOC ## POST /api/v1/role/create ### Description Creates a new role. Requires the role name and optionally accepts a description. ### Method POST ### Endpoint /api/v1/role/create #### Request Body - **name** (string) - Required - The name of the role. - **desc** (string) - Optional - The description of the role. ### Request Example ```json { "name": "admin" } ``` ### Response #### Success Response (200) - **code** (integer) - The status code, indicating success. - **msg** (string) - A message indicating the result of the operation. - **data** (...) - The created role details. #### Response Example ```json { "code": 200, "msg": "success", "data": ... } ``` #### Error Response - **code** (integer) - The status code, indicating an error (e.g., 400, 401, 403, 404, 500). - **msg** (string) - A message describing the error. - **data** (null) - Null value for error responses. #### Error Response Example ```json { "code": 400, "msg": "错误信息", "data": null } ``` ### Usage Example (cURL) ```bash curl -X POST "http://localhost:8000/api/v1/role/create" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"name": "admin"}' ``` ### Usage Example (Python requests) ```python import requests headers = { "Authorization": "Bearer " } data = { "name": "admin", } response = requests.post( "http://localhost:8000/api/v1/role/create", headers=headers, json=data ) print(response.json()) ``` ``` -------------------------------- ### Add New Feature: Product API Endpoint (Python) Source: https://jiayuxu0.github.io/FastAPI-Template/architecture Illustrates adding a new API endpoint for creating products. It uses FastAPI's dependency injection to provide the `ProductService` to the endpoint handler. ```python @router.post("/products") async def create_product( product_data: ProductCreate, product_service: ProductService = Depends(get_product_service) ): return await product_service.create(product_data) ``` -------------------------------- ### 版本信息 - API (cURL) Source: https://jiayuxu0.github.io/FastAPI-Template/api/base 使用cURL命令向/api/v1/base/version端点发送GET请求,以获取API版本信息。该请求不需要请求体。 ```bash curl -X GET "http://localhost:8000/api/v1/base/version" ``` -------------------------------- ### Test database connection in FastAPI Source: https://jiayuxu0.github.io/FastAPI-Template/faq Write an async function to test database connectivity. Use get_db_connection from core.database. Print success or error message. ```python # 测试数据库连接 from src.core.database import get_db_connection async def test_db(): try: conn = await get_db_connection() print("数据库连接成功") except Exception as e: print(f"数据库连接失败: {e}") ``` -------------------------------- ### 查看用户信息 - API (cURL) Source: https://jiayuxu0.github.io/FastAPI-Template/api/base 使用cURL命令向/api/v1/base/userinfo端点发送GET请求,以查看当前用户的信息。该请求不需要请求体。 ```bash curl -X GET "http://localhost:8000/api/v1/base/userinfo" ``` -------------------------------- ### Add new asynchronous test for FastAPI endpoint Source: https://jiayuxu0.github.io/FastAPI-Template/faq Create a new test function in tests/ directory using pytest and AsyncClient. Test user creation endpoint. Assert the response status. ```python import pytest from httpx import AsyncClient from src.main import app @pytest.mark.asyncio async def test_create_user(): async with AsyncClient(app=app, base_url="http://test") as ac: response = await ac.post("/api/v1/users/create", json={ "username": "testuser", "password": "password123" }) assert response.status_code == 200 ``` -------------------------------- ### 获取访问Token - API (cURL) Source: https://jiayuxu0.github.io/FastAPI-Template/api/base 使用cURL命令向/api/v1/base/access_token端点发送POST请求,以获取访问令牌。需要提供JSON格式的用户名和密码。 ```bash curl -X POST "http://localhost:8000/api/v1/base/access_token" \ -H "Content-Type: application/json" \ -d '{"username": "admin", "password": "password123"}' ``` -------------------------------- ### Resolve migration failures with Aerich Source: https://jiayuxu0.github.io/FastAPI-Template/faq Check migration history, optionally downgrade, fix issues, then regenerate and apply migrations. Manual intervention may be needed. Applicable when aerich upgrade fails. ```shell # 查看迁移历史 uv run aerich history # 如果需要回滚 uv run aerich downgrade # 手动修复后重新迁移 uv run aerich migrate --name "fix_migration" uv run aerich upgrade ``` -------------------------------- ### Delete User via API with cURL and Python Source: https://jiayuxu0.github.io/FastAPI-Template/api/users This example shows how to delete a user using a DELETE request to /api/v1/users/delete, requiring an authorization Bearer token in headers. It depends on cURL for command-line execution or the Python requests library for code-based requests. Outputs a JSON response with success or error codes like 200, 400, etc., potentially limited by user permissions and ID validity. ```curl curl -X DELETE "http://localhost:8000/api/v1/users/delete" \ -H "Authorization: Bearer " ``` ```python import requests headers = { "Authorization": "Bearer " } response = requests.delete( "http://localhost:8000/api/v1/users/delete", headers=headers ) print(response.json()) ``` -------------------------------- ### List Roles - cURL Source: https://jiayuxu0.github.io/FastAPI-Template/api/role Demonstrates how to list roles using a cURL request with optional query parameters for pagination and filtering by role name. Requires an authorization token. ```bash curl -X GET "http://localhost:8000/api/v1/role/list" -H "Authorization: Bearer " ```