================ CODE SNIPPETS ================ TITLE: Install FastAPI with All Dependencies DESCRIPTION: Installs FastAPI along with all optional dependencies, providing a comprehensive set of features. This is a convenient way to get started with most functionalities. SOURCE: https://fastapi.tiangolo.com/em/tutorial LANGUAGE: bash CODE: ``` pip install "fastapi[all]" ``` -------------------------------- TITLE: Install FastAPI with Standard Extras (pip) DESCRIPTION: This command installs the FastAPI package along with its standard extra dependencies. It demonstrates how packages can have optional dependencies that can be installed together. This command is provided as an example of package installation and should not be run without understanding its implications. SOURCE: https://fastapi.tiangolo.com/de/virtual-environments LANGUAGE: bash CODE: ``` pip install "fastapi[standard]" ``` -------------------------------- TITLE: FastAPI CLI Installation and Usage Example DESCRIPTION: Demonstrates how to install and use the new FastAPI CLI for development. It shows the command-line interface for starting a development server and provides output indicating the server address and API documentation links. SOURCE: https://fastapi.tiangolo.com/em/release-notes LANGUAGE: bash CODE: ``` $ pip install --upgrade fastapi $ fastapi dev main.py ╭────────── FastAPI CLI - Development mode ───────────╮ │ │ │ Serving at: http://127.0.0.1:8000 │ │ │ │ API docs: http://127.0.0.1:8000/docs │ │ │ │ Running in development mode, for production use: │ │ │ │ fastapi run │ │ │ ╰─────────────────────────────────────────────────────╯ INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [2248755] using WatchFiles INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` -------------------------------- TITLE: Install FastAPI with standard extras DESCRIPTION: Installs the FastAPI package along with standard extras. This command can be used when you need to quickly install packages without a requirements file. It can be executed using either pip or uv. SOURCE: https://fastapi.tiangolo.com/de/virtual-environments LANGUAGE: bash CODE: ``` pip install "fastapi[standard]" ``` LANGUAGE: bash CODE: ``` uv pip install "fastapi[standard]" ``` -------------------------------- TITLE: Run FastAPI App with Uvicorn DESCRIPTION: This Python code demonstrates a basic FastAPI application and how to run it using the Uvicorn server. It defines a simple root endpoint and uses `uvicorn.run()` to start the server when the script is executed directly. Ensure Python 3.8+ is installed. SOURCE: https://fastapi.tiangolo.com/em/tutorial/debugging LANGUAGE: python CODE: ``` import uvicorn from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): a = "a" b = "b" + a return {"hello world": b} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- TITLE: FastAPI Application Setup and Endpoints DESCRIPTION: Defines a FastAPI application instance and sets up several endpoints: `/token` for login, `/users/me/` to get the current user, `/users/me/items/` for items with scope protection, and `/status/` for system status. SOURCE: https://fastapi.tiangolo.com/uk/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from fastapi import FastAPI, Depends from fastapi.security import OAuth2PasswordRequestForm from datetime import timedelta # Assuming app, authenticate_user, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES, Token, User, get_current_active_user, get_current_user are defined app = FastAPI() @app.post("/token") async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( data={"sub": user.username, "scope": " ".join(form_data.scopes)}, expires_delta=access_token_expires, ) return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) async def read_users_me(current_user: User = Depends(get_current_active_user)): return current_user @app.get("/users/me/items/") async def read_own_items( current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] @app.get("/status/") async def read_system_status(current_user: User = Depends(get_current_user)): return {"status": "ok"} ``` -------------------------------- TITLE: Update pip using Python DESCRIPTION: Updates the pip package installer to the latest version. This is recommended to be done once after creating a virtual environment to avoid installation issues. It requires an active virtual environment. SOURCE: https://fastapi.tiangolo.com/de/virtual-environments LANGUAGE: bash CODE: ``` python -m pip install --upgrade pip ``` -------------------------------- TITLE: Install Specific Package Version (pip) DESCRIPTION: This command installs a specific version of a Python package using pip. It's useful for ensuring project compatibility when dependencies have version conflicts. Be aware that installing globally can lead to issues with other projects or system Python. SOURCE: https://fastapi.tiangolo.com/de/virtual-environments LANGUAGE: bash CODE: ``` pip install "harry==1" ``` LANGUAGE: bash CODE: ``` pip install "harry==3" ``` -------------------------------- TITLE: Run Python program DESCRIPTION: Executes a Python script named main.py using the Python interpreter within the currently active virtual environment. This ensures that the script uses the installed packages. SOURCE: https://fastapi.tiangolo.com/de/virtual-environments LANGUAGE: bash CODE: ``` python main.py ``` -------------------------------- TITLE: FastAPI Application Setup DESCRIPTION: Basic setup for a FastAPI application, including importing necessary modules and initializing the FastAPI instance. This serves as the foundation for the authentication endpoints. SOURCE: https://fastapi.tiangolo.com/pt/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"message": "Welcome to the JWT Auth API"} ``` -------------------------------- TITLE: Basic FastAPI App Setup DESCRIPTION: This snippet demonstrates the fundamental steps to initialize a FastAPI application and define a simple root endpoint. SOURCE: https://fastapi.tiangolo.com/es/tutorial/first-steps LANGUAGE: APIDOC CODE: ``` ## GET / ### Description This endpoint serves as the root of the API and returns a simple greeting message. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **message** (string) - A greeting message. #### Response Example ```json { "message": "Hello World" } ``` ``` -------------------------------- TITLE: Install and Run Pytest for FastAPI Tests DESCRIPTION: This section details how to install the pytest framework, which is commonly used for running the tests written with FastAPI's TestClient. It provides the command-line instructions for installation and execution, along with an example of the expected output when tests are run successfully. SOURCE: https://fastapi.tiangolo.com/em/tutorial/testing LANGUAGE: bash CODE: ``` pip install pytest pytest ``` -------------------------------- TITLE: FastAPI Application Setup DESCRIPTION: Basic FastAPI application setup with title, description, version, contact, and license information. Includes a sample endpoint for reading items. SOURCE: https://fastapi.tiangolo.com/em/tutorial/metadata LANGUAGE: APIDOC CODE: ``` ## FastAPI Application Setup ### Description This section demonstrates how to initialize a FastAPI application with metadata such as title, description, version, terms of service, contact information, and license details. It also includes a simple GET endpoint. ### Method GET ### Endpoint /items/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **name** (string) - The name of the item. #### Response Example ```json [ { "name": "Katana" } ] ``` ``` -------------------------------- TITLE: FastAPI Application Setup DESCRIPTION: This section explains how to set up a basic FastAPI application and run it using Uvicorn. It covers the core components like the FastAPI instance and running the server. SOURCE: https://fastapi.tiangolo.com/em/tutorial/first-steps LANGUAGE: APIDOC CODE: ``` ## FastAPI Application Setup ### Description This section explains how to set up a basic FastAPI application and run it using Uvicorn. It covers the core components like the FastAPI instance and running the server. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```python from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} ``` ### Running the Server ```bash fast →uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [28720] INFO: Started server process [28722] INFO: Waiting for application startup. INFO: Application startup complete. ``` **Explanation:** - `main`: Refers to the `main.py` file. - `app`: Refers to the `app = FastAPI()` instance within `main.py`. - `--reload`: Enables hot-reloading for development. ``` -------------------------------- TITLE: Install email-validator for Pydantic EmailStr DESCRIPTION: Provides commands to install the `email-validator` library, which is a dependency for using the `EmailStr` type in Pydantic models. It can be installed directly or as part of Pydantic. SOURCE: https://fastapi.tiangolo.com/es/tutorial/response-model LANGUAGE: bash CODE: ``` $ pip install email-validator ``` LANGUAGE: bash CODE: ``` $ pip install "pydantic[email]" ``` -------------------------------- TITLE: FastAPI Setup and Dependencies DESCRIPTION: Initializes a FastAPI application instance and sets up OAuth2 authentication with a token URL. It also includes a dummy user database. SOURCE: https://fastapi.tiangolo.com/zh/tutorial/security/simple-oauth2 LANGUAGE: python CODE: ``` from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from pydantic import BaseModel fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "fakehashedsecret", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Wonderson", "email": "alice@example.com", "hashed_password": "fakehashedsecret2", "disabled": True, }, } app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") ``` -------------------------------- TITLE: GET /items/ DESCRIPTION: Retrieves a specific item by its ID or a random item if no ID is provided. The ID must start with 'isbn-' or 'imdb-'. SOURCE: https://fastapi.tiangolo.com/de/tutorial/query-params-str-validations LANGUAGE: APIDOC CODE: ``` ## GET /items/ ### Description Retrieves a specific item by its ID or a random item if no ID is provided. The ID must start with 'isbn-' or 'imdb-'. ### Method GET ### Endpoint /items/ ### Parameters #### Query Parameters - **id** (str | None) - Optional - The unique identifier for the item. Must start with 'isbn-' or 'imdb-'. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **id** (str) - The ID of the retrieved item. - **name** (str) - The name of the retrieved item. #### Response Example { "id": "isbn-9781529046137", "name": "The Hitchhiker's Guide to the Galaxy" } ``` -------------------------------- TITLE: Main FastAPI Application Setup DESCRIPTION: Configuration and setup of the main FastAPI application, including including routers and global dependencies. SOURCE: https://fastapi.tiangolo.com/pt/tutorial/bigger-applications LANGUAGE: APIDOC CODE: ``` ## Main Application Setup ### Description This section details the main `FastAPI` application setup in `app/main.py`, including importing `FastAPI`, setting global dependencies, and including various routers. ### Method N/A (Application configuration) ### Endpoint N/A ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - Root Endpoint - **message** (str) - A greeting message. #### Response Example (Root Endpoint) ```json { "message": "Hello Bigger Applications!" } ``` ### Application Configuration Details: - **Global Dependencies**: `app = FastAPI(dependencies=[Depends(get_query_token)])` sets a query token as a global dependency for all requests. - **Including Routers**: Routers for users, items, and admin are included. - The admin router is prefixed with `/admin`, tagged as `admin`, has its own header token dependency, and a custom teapot response. - **Root Endpoint**: A simple GET request to `/` returns a welcome message. ``` -------------------------------- TITLE: GET /items/ DESCRIPTION: Retrieves an item by its ID. If no ID is provided, a random item is returned. The ID must start with 'isbn-' or 'imdb-'. SOURCE: https://fastapi.tiangolo.com/de/tutorial/query-params-str-validations LANGUAGE: APIDOC CODE: ``` ## GET /items/ ### Description Retrieves an item by its ID. If no ID is provided, a random item is returned. The ID must start with 'isbn-' or 'imdb-'. ### Method GET ### Endpoint /items/ ### Parameters #### Query Parameters - **id** (string) - Optional - The ID of the item to retrieve. Must start with 'isbn-' or 'imdb-'. ### Request Example GET /items/?id=isbn-9781529046137 ### Response #### Success Response (200) - **id** (string) - The ID of the retrieved item. - **name** (string) - The name of the retrieved item. #### Response Example { "id": "isbn-9781529046137", "name": "The Hitchhiker's Guide to the Galaxy" } ``` -------------------------------- TITLE: GET /users/{username} DESCRIPTION: An example path operation to retrieve user information based on a username. This endpoint is part of the FastAPI application setup. SOURCE: https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets LANGUAGE: APIDOC CODE: ``` ## GET /users/{username} ### Description Retrieves user information by username. ### Method GET ### Endpoint /users/{username} ### Parameters #### Path Parameters - **username** (str) - Required - The username of the user to retrieve. ### Request Example (No request body for this GET request) ### Response #### Success Response (200) - **message** (str) - A greeting message including the username. #### Response Example ```json { "message": "Hello {username}" } ``` ``` -------------------------------- TITLE: Deactivate virtual environment DESCRIPTION: Deactivates the currently active virtual environment. After deactivation, running 'python' will use the system's global Python installation instead of the one in the virtual environment. SOURCE: https://fastapi.tiangolo.com/de/virtual-environments LANGUAGE: bash CODE: ``` deactivate ``` -------------------------------- TITLE: Run FastAPI Development Server with a Tutorial App DESCRIPTION: Starts the FastAPI development server using `fastapi dev` with a specified Python file. This is useful for running documentation examples as applications. SOURCE: https://fastapi.tiangolo.com/contributing LANGUAGE: bash CODE: ``` fastapi dev tutorial001.py ``` -------------------------------- TITLE: GET / DESCRIPTION: This endpoint serves a simple 'Hello World' message. It's a basic example demonstrating how to define a root endpoint in FastAPI. SOURCE: https://fastapi.tiangolo.com/em/tutorial/first-steps LANGUAGE: APIDOC CODE: ``` ## GET / ### Description This endpoint serves a simple 'Hello World' message. It's a basic example demonstrating how to define a root endpoint in FastAPI. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **message** (string) - A greeting message. #### Response Example ```json { "message": "Hello World" } ``` ``` -------------------------------- TITLE: Example User Endpoint DESCRIPTION: A simple GET endpoint demonstrating how to define a path operation for retrieving user information. This endpoint is included to show a basic API functionality alongside the documentation setup. SOURCE: https://fastapi.tiangolo.com/ko/how-to/custom-docs-ui-assets LANGUAGE: APIDOC CODE: ``` ## Example User Endpoint ### Description An example endpoint to retrieve a user by their username. This demonstrates a typical API resource endpoint. ### Method GET ### Endpoint `/users/{username}` ### Parameters #### Path Parameters - **username** (str) - Required - The username of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET "http://your-api-url/users/john_doe" ``` ### Response #### Success Response (200) - **message** (str) - A message indicating the username. #### Response Example ```json { "message": "Hello john_doe" } ``` ``` -------------------------------- TITLE: Installing FastAPI without Cloud CLI DESCRIPTION: This command installs FastAPI with standard dependencies but excludes the fastapi-cloud-cli. This is useful if you do not intend to use FastAPI Cloud for deployment. SOURCE: https://fastapi.tiangolo.com/tr/tutorial LANGUAGE: bash CODE: ``` pip install "fastapi[standard-no-fastapi-cloud-cli]" ``` -------------------------------- TITLE: FastAPI Route Definition Example DESCRIPTION: Shows how to define a basic GET route in FastAPI. This example illustrates path parameters and query parameters. SOURCE: https://fastapi.tiangolo.com/reference/parameters LANGUAGE: python CODE: ``` from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} ``` -------------------------------- TITLE: Create Project Directory DESCRIPTION: This command sequence creates a new directory for your Python project and navigates into it. It's the first step in setting up a new project. SOURCE: https://fastapi.tiangolo.com/fa/virtual-environments LANGUAGE: bash CODE: ``` cd mkdir code cd code mkdir awesome-project cd awesome-project ``` -------------------------------- TITLE: GET /users/me - User Authentication Example DESCRIPTION: An example endpoint demonstrating how to use HTTP Digest authentication to get the current user's credentials. It requires a valid digest authorization header. SOURCE: https://fastapi.tiangolo.com/ja/reference/security LANGUAGE: APIDOC CODE: ``` ## GET /users/me ### Description This endpoint retrieves the credentials of the currently authenticated user using HTTP Digest authentication. ### Method GET ### Endpoint /users/me ### Parameters #### Query Parameters None #### Request Body None ### Request Example ``` # No specific request body, but requires Authorization header # Example: Authorization: Digest username="user", realm="myrealm", nonce="...", uri="...", response="..." ``` ### Response #### Success Response (200) - **scheme** (string) - The authentication scheme (e.g., 'Digest'). - **credentials** (string) - The provided digest credentials. #### Response Example ```json { "scheme": "Digest", "credentials": "username=\"user\", realm=\"myrealm\", nonce=\"...\", uri=\"...\", response=\"...\"" } ``` #### Error Response (401) - **detail** (string) - "Not authenticated" or other relevant error message if credentials are missing or invalid. ``` -------------------------------- TITLE: FastAPI Application Setup DESCRIPTION: This section demonstrates how to create a main FastAPI application and mount a sub-API. It includes the Python code for defining both the main app and the sub-app, and how to connect them. SOURCE: https://fastapi.tiangolo.com/em/advanced/sub-applications LANGUAGE: APIDOC CODE: ``` ## FastAPI Application Setup ### Description This code demonstrates the basic structure of a FastAPI application, including how to define a main application instance and mount a separate sub-application under a specific path. ### Method Not Applicable (Code Example) ### Endpoint Not Applicable (Code Example) ### Parameters None ### Request Body None ### Request Example ```python from fastapi import FastAPI app = FastAPI() @app.get("/app") def read_main(): return {"message": "Hello World from main app"} subapi = FastAPI() @subapi.get("/sub") def read_sub(): return {"message": "Hello World from sub API"} app.mount("/subapi", subapi) ``` ### Response #### Success Response (200) Not Applicable (Code Example) #### Response Example Not Applicable (Code Example) ``` -------------------------------- TITLE: Full-Stack Examples DESCRIPTION: References to full-stack examples using FastAPI. SOURCE: https://fastapi.tiangolo.com/em/alternatives LANGUAGE: APIDOC CODE: ``` ## Full-Stack Examples ### Description FastAPI can be used as the backend for full-stack applications. Several example repositories demonstrate how to build full-stack applications with FastAPI, often paired with frontend frameworks and databases. ### Resources - [Full-Stack Template (FastAPI)](https://github.com/tiangolo/full-stack) - [Full-Stack Template (FastAPI + Flask + Couchbase)](https://github.com/tiangolo/full-stack-flask-couchbase) - [Full-Stack Template (FastAPI + Flask + CouchDB)](https://github.com/tiangolo/full-stack-flask-couchdb) These examples provide practical guidance on setting up and deploying full-stack applications utilizing FastAPI. ``` -------------------------------- TITLE: GET /status/ - Get System Status DESCRIPTION: Checks the current status of the system. SOURCE: https://fastapi.tiangolo.com/uk/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## GET /status/ ### Description Provides the current operational status of the system. Requires authentication. ### Method GET ### Endpoint /status/ ### Parameters N/A (Authentication is done via Bearer token in the Authorization header) ### Response #### Success Response (200) - **status** (string) - Indicates the system status, typically 'ok'. #### Response Example ```json { "status": "ok" } ``` #### Error Response (401) - **detail** (string) - "Could not validate credentials" ``` -------------------------------- TITLE: Main Application Setup DESCRIPTION: Details the main FastAPI application setup, including importing and including routers, and defining a root endpoint. Global dependencies and router-specific configurations are also highlighted. SOURCE: https://fastapi.tiangolo.com/tutorial/bigger-applications LANGUAGE: APIDOC CODE: ``` ## GET / ### Description Returns a welcome message from the root endpoint. ### Method GET ### Endpoint / ### Parameters None ### Request Body None ### Response #### Success Response (200) - **message** (str) - A greeting message. #### Response Example ```json { "message": "Hello Bigger Applications!" } ``` ## Include Routers ### Description Includes various routers into the main FastAPI application, defining prefixes, tags, dependencies, and responses for each. ### Endpoints Included: - **Users Router**: Included without a specific prefix or tags. - **Items Router**: Included with a prefix of `/items` and tagged as `items`. - **Admin Router**: Included with a prefix of `/admin`, tagged as `admin`, and has specific dependencies and responses. ### Global Dependencies: - `get_query_token` is applied globally to all endpoints. ### Router Specific Configurations: - **Admin Router**: - `prefix`: `/admin` - `tags`: `["admin"]` - `dependencies`: `[Depends(get_token_header)]` - `responses`: `{418: {"description": "I'm a teapot"}}` ### Example of Application Structure: ```python from fastapi import Depends, FastAPI from .dependencies import get_query_token, get_token_header from .internal import admin from .routers import items, users app = FastAPI(dependencies=[Depends(get_query_token)]) app.include_router(users.router) app.include_router(items.router) app.include_router( admin.router, prefix="/admin", tags=["admin"], dependencies=[Depends(get_token_header)], responses={418: {"description": "I'm a teapot"}}, ) @app.get("/") async def root(): return {"message": "Hello Bigger Applications!"} ``` ``` -------------------------------- TITLE: FastAPI Application Setup DESCRIPTION: Initializes the FastAPI application and sets up the database table creation on startup event. This includes defining the FastAPI instance and hooking into the startup event. SOURCE: https://fastapi.tiangolo.com/tutorial/sql-databases LANGUAGE: python CODE: ``` app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() ``` -------------------------------- TITLE: GET /status/ - Get System Status DESCRIPTION: Retrieves the current status of the system. SOURCE: https://fastapi.tiangolo.com/pt/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## GET /status/ ### Description Retrieves the current operational status of the system. This endpoint is protected and requires authentication. ### Method GET ### Endpoint /status/ ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "Authorization": "Bearer YOUR_ACCESS_TOKEN" } ``` ### Response #### Success Response (200) - A status message indicating the system's operational state. #### Response Example ```json { "status": "operational" } ``` #### Error Response (401) - **detail** (string) - "Could not validate credentials" ``` -------------------------------- TITLE: GET /status/ - Get System Status DESCRIPTION: Checks the current status of the system. SOURCE: https://fastapi.tiangolo.com/pt/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## GET /status/ ### Description Checks the current status of the system. Requires general user authentication (no specific scope needed beyond being authenticated). ### Method GET ### Endpoint /status/ ### Parameters #### Query Parameters None ### Request Example (No request body needed, authentication is via Authorization header) ### Response #### Success Response (200) - **status** (string) - The status of the system (e.g., "ok"). #### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- TITLE: Initialize FastAPI Application with Parameters DESCRIPTION: Demonstrates initializing a FastAPI application with various configuration parameters. This includes settings for OpenAPI generation (title, summary, description, version, contact, license, terms_of_service), URL configurations (openapi_url, docs_url, redoc_url), and server details. It also shows how to set up external documentation and handle extra keyword arguments. SOURCE: https://fastapi.tiangolo.com/de/reference/fastapi LANGUAGE: python CODE: ``` from typing import Optional, Dict, Any from fastapi import FastAPI from fastapi.utils import Doc from starlette.datastructures import State from fastapi import routing import logging logger = logging.getLogger(__name__) # Assume Doc, State, routing are imported and available # Placeholder for Doc, State, routing if not actually defined in the context class Doc: def __init__(self, description: str): self.description = description class State: pass class APIRouter: pass def FastAPI( *, # Other parameters omitted for brevity debug: bool = False, title: str = "FastAPI", summary: str = "FastAPI description", description: str = "", version: str = "0.1.0", terms_of_service: Optional[str] = None, contact: Optional[Dict[str, str]] = None, license_info: Optional[Dict[str, str]] = None, openapi_url: Optional[str] = "/openapi.json", openapi_tags: Optional[list] = None, root_path_in_servers: bool = True, docs_url: str = "/docs", redoc_url: str = "/redoc", swagger_ui_oauth2_redirect_url: Optional[str] = None, swagger_ui_init_oauth: Optional[Dict[str, Any]] = None, swagger_ui_parameters: Optional[Dict[str, Any]] = None, servers: Optional[list] = None, separate_input_output_schemas: bool = True, openapi_external_docs: Optional[Dict[str, Any]] = None, webhooks: Optional[routing.APIRouter] = None, root_path: str = "", openapi_prefix: str = "", # Deprecated **extra: Annotated[Any, Doc("Extra keyword arguments to be stored in the app, not used by FastAPI anywhere.")] ) -> None: self.debug = debug self.title = title self.summary = summary self.description = description self.version = version self.terms_of_service = terms_of_service self.contact = contact self.license_info = license_info self.openapi_url = openapi_url self.openapi_tags = openapi_tags self.root_path_in_servers = root_path_in_servers self.docs_url = docs_url self.redoc_url = redoc_url self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url self.swagger_ui_init_oauth = swagger_ui_init_oauth self.swagger_ui_parameters = swagger_ui_parameters self.servers = servers or [] self.separate_input_output_schemas = separate_input_output_schemas self.openapi_external_docs = openapi_external_docs self.extra = extra self.openapi_version: Annotated[str, Doc("The version string of OpenAPI.")] = "3.1.0" self.openapi_schema: Optional[Dict[str, Any]] = None if self.openapi_url: assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'" if openapi_prefix: logger.warning( '"openapi_prefix" has been deprecated in favor of "root_path", which ' \ "follows more closely the ASGI standard, is simpler, and more " \ "automatic. Check the docs at " \ "https://fastapi.tiangolo.com/advanced/sub-applications/" ) self.webhooks: Annotated[routing.APIRouter, Doc("The `app.webhooks` attribute is an `APIRouter` with the *path operations* that will be used just for documentation of webhooks.")] = webhooks or routing.APIRouter() self.root_path = root_path or openapi_prefix self.state: Annotated[State, Doc("A state object for the application.")] = State() self.dependency_overrides: Dict[callable, callable] = {} # Example Usage: app = FastAPI( title="My Awesome API", version="1.0.0", description="This is a very awesome API to demonstrate FastAPI features.", contact={"name": "Support Team", "url": "http://www.example.com/support"}, license_info={"name": "MIT License", "url": "http://www.example.com/license"}, openapi_external_docs={ "description": "External API Documentation", "url": "https://docs.example.com/external", }, servers=[ {"url": "http://localhost:8000", "description": "Development Server"}, {"url": "https://api.example.com", "description": "Production Server"}, ], docs_url="/api/docs", redoc_url="/api/redoc", ) ``` -------------------------------- TITLE: GET /users/me/ - Get Current User DESCRIPTION: Retrieves the details of the currently authenticated user. SOURCE: https://fastapi.tiangolo.com/ko/tutorial/security/oauth2-jwt LANGUAGE: APIDOC CODE: ``` ## GET /users/me/ ### Description Retrieves the details of the currently authenticated user based on the provided access token. ### Method GET ### Endpoint /users/me/ ### Parameters #### Header Parameters - **Authorization** (str) - Required - Bearer token for authentication (e.g., `Bearer YOUR_ACCESS_TOKEN`). ### Response #### Success Response (200) - **username** (str) - The username of the current user. - **email** (str | None) - The email of the current user. - **full_name** (str | None) - The full name of the current user. - **disabled** (bool | None) - Indicates if the user account is disabled. #### Response Example ```json { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false } ``` #### Error Response (401) - **detail** (str) - "Could not validate credentials" ``` -------------------------------- TITLE: FastAPI Main Application Setup (Python) DESCRIPTION: Sets up the main FastAPI application instance, including global dependencies and including other routers. This demonstrates how to assemble different parts of a larger FastAPI application. SOURCE: https://fastapi.tiangolo.com/uk/tutorial/bigger-applications LANGUAGE: python CODE: ``` from fastapi import Depends, FastAPI from .dependencies import get_query_token, get_token_header from .internal import admin from .routers import items, users app = FastAPI(dependencies=[Depends(get_query_token)]) app.include_router(users.router) app.include_router(items.router) app.include_router( admin.router, prefix="/admin", tags=["admin"], dependencies=[Depends(get_token_header)], responses={418: {"description": "I'm a teapot"}}, ) @app.get("/") async def root(): return {"message": "Hello Bigger Applications!"} ``` -------------------------------- TITLE: Installation DESCRIPTION: Install FastAPI and an ASGI server like Uvicorn. For standard features, use `fastapi[standard]`. SOURCE: https://fastapi.tiangolo.com/em LANGUAGE: APIDOC CODE: ``` ## Installation FastAPI requires Python 3.7+. It is recommended to install it with an ASGI server like Uvicorn. ### Install FastAPI ```bash fastapi fast →pip install "fastapi[standard]" restart ↻ ``` ### Install Uvicorn ```bash fast →pip install "uvicorn[standard]" restart ↻ ``` ``` -------------------------------- TITLE: GET /users/me/ - Get Current User DESCRIPTION: Retrieves the details of the currently authenticated user. SOURCE: https://fastapi.tiangolo.com/ko/tutorial/security/oauth2-jwt LANGUAGE: APIDOC CODE: ``` ## GET /users/me/ ### Description Retrieves the details of the currently authenticated user based on the provided access token. ### Method GET ### Endpoint /users/me/ ### Parameters #### Header Parameters - **Authorization** (str) - Required - Bearer token for authentication (e.g., `Bearer YOUR_ACCESS_TOKEN`). ### Response #### Success Response (200) - **username** (str) - The username of the user. - **email** (str) - The email address of the user. - **full_name** (str) - The full name of the user. - **disabled** (bool) - Indicates if the user account is disabled. #### Response Example ```json { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false } ``` #### Error Response (401) - **detail** (str) - "Could not validate credentials" ``` -------------------------------- TITLE: GET /users/me/ - Get Current User DESCRIPTION: Retrieves the details of the currently authenticated user. SOURCE: https://fastapi.tiangolo.com/ja/tutorial/security/oauth2-jwt LANGUAGE: APIDOC CODE: ``` ## GET /users/me/ ### Description Retrieves the details of the currently authenticated user based on the provided access token. ### Method GET ### Endpoint /users/me/ ### Parameters #### Header Parameters - **Authorization** (str) - Required - Bearer token for authentication (e.g., `Bearer YOUR_ACCESS_TOKEN`). ### Response #### Success Response (200) - **username** (str) - The username of the current user. - **email** (str) - The email address of the current user. - **full_name** (str) - The full name of the current user. - **disabled** (bool) - Indicates if the user account is disabled. #### Response Example ```json { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false } ``` #### Error Response (401) - **detail** (str) - "Could not validate credentials" - **headers** (dict) - {"WWW-Authenticate": "Bearer"} ``` -------------------------------- TITLE: GET /users/me/ - Get Current User DESCRIPTION: Retrieves the details of the currently authenticated user. SOURCE: https://fastapi.tiangolo.com/ja/tutorial/security/oauth2-jwt LANGUAGE: APIDOC CODE: ``` ## GET /users/me/ ### Description Retrieves the details of the currently authenticated user based on the provided access token. ### Method GET ### Endpoint /users/me/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **username** (string) - The username of the user. - **email** (string) - The email address of the user. - **full_name** (string) - The full name of the user. - **disabled** (boolean) - Indicates if the user account is disabled. #### Response Example ```json { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false } ``` #### Error Response (401) - **detail** (string) - Describes the authentication failure (e.g., 'Could not validate credentials'). #### Error Response (400) - **detail** (string) - Describes the user status issue (e.g., 'Inactive user'). ``` -------------------------------- TITLE: Serve Built FastAPI Documentation DESCRIPTION: This command serves the built FastAPI documentation, including all translations. It's intended for previewing a site with translations already built and requires the 'build-all' command to be run first. Note: For development, 'mkdocs serve' is recommended. SOURCE: https://fastapi.tiangolo.com/contributing LANGUAGE: bash CODE: ``` python ./scripts/docs.py serve ``` -------------------------------- TITLE: Example User Endpoint DESCRIPTION: A simple example endpoint demonstrating a standard GET request. SOURCE: https://fastapi.tiangolo.com/uk/how-to/custom-docs-ui-assets LANGUAGE: APIDOC CODE: ``` ## Example User Endpoint ### Description An example endpoint that retrieves user information based on a provided username. ### Method GET ### Endpoint `/users/{username}` ### Parameters #### Path Parameters - **username** (str) - Required - The username of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```bash GET /users/john_doe ``` ### Response #### Success Response (200) - **message** (str) - A greeting message including the username. #### Response Example ```json { "message": "Hello john_doe" } ``` ``` -------------------------------- TITLE: GET /items/ DESCRIPTION: Defines a path operation for an HTTP GET request. This example demonstrates how to create a simple GET endpoint that returns a list of items. SOURCE: https://fastapi.tiangolo.com/ko/reference/fastapi LANGUAGE: APIDOC CODE: ``` ## GET /items/ ### Description Defines a path operation using an HTTP GET request. This example demonstrates how to create a simple GET endpoint that returns a list of items. ### Method GET ### Endpoint /items/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body for GET" } ``` ### Response #### Success Response (200) - **name** (string) - The name of the item. #### Response Example ```json [ { "name": "Empanada" }, { "name": "Arepa" } ] ``` ``` -------------------------------- TITLE: Main Application Setup DESCRIPTION: Configures the main FastAPI application, including including other routers (users, items, admin) and setting up global dependencies and prefixes. SOURCE: https://fastapi.tiangolo.com/ja/tutorial/bigger-applications LANGUAGE: APIDOC CODE: ``` ## Root Endpoint ### Description A simple root endpoint for the application. ### Method GET ### Endpoint / ### Parameters ### Request Example ### Response #### Success Response (200) - **message**: str - A greeting message. #### Response Example ```json { "message": "Hello Bigger Applications!" } ``` ## Admin API Router ### Description Provides endpoints for administrative functions, secured by a header token and with a custom teapot response. ### Method Included via `app.include_router` with prefix, tags, dependencies, and responses. ### Endpoint /admin ### Parameters ### Request Example ### Response #### Error Response (418) - **description**: "I'm a teapot" ### Tags - admin ### Dependencies - Depends(get_token_header) ### Responses - 418: I'm a teapot ## Global Dependencies ### Description Global dependencies applied to all endpoints in the application. ### Dependencies - Depends(get_query_token) ``` -------------------------------- TITLE: GET /users/me/ - Get Current User DESCRIPTION: Retrieves information about the currently authenticated user. SOURCE: https://fastapi.tiangolo.com/uk/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## GET /users/me/ ### Description Retrieves information about the currently authenticated user, requiring the 'me' scope. ### Method GET ### Endpoint /users/me/ ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **username** (string) - The username of the current user. - **email** (string) - The email of the current user. - **full_name** (string) - The full name of the current user. - **disabled** (boolean) - Indicates if the user account is disabled. #### Response Example ```json { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false } ``` ``` -------------------------------- TITLE: Initialize FastAPI with OpenAPI Settings DESCRIPTION: Demonstrates initializing a FastAPI application with various OpenAPI related configurations. It includes options for title, summary, description, version, contact, license, and documentation URLs. SOURCE: https://fastapi.tiangolo.com/ko/reference/fastapi LANGUAGE: python CODE: ``` from fastapi import FastAPI from typing import Optional, Dict, Any app = FastAPI( title="My API", summary="A short summary of my API.", description="This is a longer description of my API.", version="0.1.0", terms_of_service="https://example.com/terms", contact={"name": "API Support", "url": "https://example.com/contact", "email": "support@example.com"}, license_info={"name": "MIT License", "url": "https://example.com/license"}, openapi_url="/openapi.json", docs_url="/docs", redoc_url="/redoc", servers=[ {"url": "https://api.example.com", "description": "Production server"}, {"url": "http://localhost:8000", "description": "Development server"} ], separate_input_output_schemas=True, openapi_external_docs={"description": "External Docs", "url": "https://example.com/external"} ) ``` -------------------------------- TITLE: GET /users/me/items/ - Get Own Items DESCRIPTION: Retrieves a list of items associated with the currently authenticated user. SOURCE: https://fastapi.tiangolo.com/zh/tutorial/security/oauth2-jwt LANGUAGE: APIDOC CODE: ``` ## GET /users/me/items/ ### Description Returns a list of items belonging to the currently authenticated user. This endpoint requires a valid JWT access token. ### Method GET ### Endpoint /users/me/items/ ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token (e.g., Bearer YOUR_ACCESS_TOKEN). ### Response #### Success Response (200) - A list of item objects, where each object contains: - **item_id** (string) - The unique identifier of the item. - **owner** (string) - The username of the item's owner. #### Response Example ```json [ { "item_id": "Foo", "owner": "johndoe" } ] ``` #### Error Response (401) - **detail** (string) - "Could not validate credentials" - **detail** (string) - "Inactive user" ``` -------------------------------- TITLE: FastAPI App Initialization Example (Python) DESCRIPTION: Demonstrates how to initialize a FastAPI application with various configuration options. This includes setting debug mode, providing API metadata like title, summary, description, and version, as well as configuring the OpenAPI URL. SOURCE: https://fastapi.tiangolo.com/uk/reference/fastapi LANGUAGE: python CODE: ``` from fastapi import FastAPI app = FastAPI( title="My Awesome API", summary="A small API for my awesome app.", description="This is a **very** detailed description of my API.", version="1.0.0", openapi_url="/api/v1/openapi.json", debug=True ) ``` -------------------------------- TITLE: Serve FastAPI Documentation Live DESCRIPTION: Builds the documentation site and watches for changes, live-reloading the documentation server. The documentation will be available at http://127.0.0.1:8008. SOURCE: https://fastapi.tiangolo.com/contributing LANGUAGE: bash CODE: ``` python ./scripts/docs.py live ``` -------------------------------- TITLE: GET /users/me/ - Get Current User DESCRIPTION: Retrieves the currently authenticated user's information. SOURCE: https://fastapi.tiangolo.com/zh/tutorial/security/oauth2-jwt LANGUAGE: APIDOC CODE: ``` ## GET /users/me/ ### Description Retrieves the information of the currently authenticated user based on the provided access token. ### Method GET ### Endpoint /users/me/ ### Parameters #### Headers - **Authorization** (str) - Required - Bearer token for authentication (e.g., "Bearer YOUR_ACCESS_TOKEN"). ### Response #### Success Response (200) - **username** (str) - The username of the current user. - **email** (str) - The email of the current user (optional). - **full_name** (str) - The full name of the current user (optional). - **disabled** (bool) - Indicates if the user account is disabled (optional). #### Response Example ```json { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false } ``` #### Error Response (401) - **detail** (str) - "Could not validate credentials" ``` -------------------------------- TITLE: Initialize FastAPI App with Description DESCRIPTION: Illustrates initializing a FastAPI application with a detailed description that supports Markdown formatting, enhancing the API documentation. SOURCE: https://fastapi.tiangolo.com/fr/reference/fastapi LANGUAGE: python CODE: ``` from fastapi import FastAPI app = FastAPI( description=""" ChimichangApp API helps you do awesome stuff. 🚀 ## Items You can **read items**. ## Users You will be able to: * **Create users** (_not implemented_). * **Read users** (_not implemented_). """) ```