### GET / Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This endpoint provides a basic 'Hello World' message from the FastAPI application. It's the default root endpoint for demonstrating application functionality. ```APIDOC ## GET / ### Description This endpoint serves as the root of the FastAPI application, returning a simple "Hello World" message. It demonstrates a basic HTTP GET request handler. ### Method GET ### Endpoint / ### Parameters #### Path Parameters No path parameters. #### Query Parameters No query parameters. #### Request Body No request body. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **message** (string) - A greeting message. #### Response Example ```json { "message": "Hello World" } ``` ``` -------------------------------- ### Create a Basic FastAPI Application Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This Python code snippet demonstrates how to initialize a FastAPI application and define a simple asynchronous GET endpoint at the root path ('/'). It returns a JSON response with 'Hello World'. This code should be saved in a file like `main.py`. ```python from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} ``` -------------------------------- ### GET / Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This endpoint serves as a basic health check or a root endpoint, returning a simple 'Hello World' message to confirm the application is running. ```APIDOC ## GET / ### Description This endpoint returns a simple 'Hello World' message. ### Method GET ### Endpoint / ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (No request body required) ### Response #### Success Response (200) - **message** (string) - The greeting message. #### Response Example { "message": "Hello World" } ``` -------------------------------- ### Initialize FastAPI Application with Custom Name and Route Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This Python example shows how to instantiate a FastAPI application with a custom variable name, `my_awesome_api`, instead of the default `app`. It also defines a basic GET route using this custom instance. ```python from fastapi import FastAPI my_awesome_api = FastAPI() @my_awesome_api.get("/") async def root(): return {"message": "Hello World"} ``` -------------------------------- ### Uvicorn Server Startup Output Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This text snippet illustrates the typical console output when Uvicorn successfully starts a FastAPI application, indicating the local address where the server is accessible and confirming that the application has started. ```plaintext 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. ``` ```plaintext INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` -------------------------------- ### Example OpenAPI Specification (openapi.json) Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This partial JSON code demonstrates the structure of the `openapi.json` file automatically generated by FastAPI. This file adheres to the OpenAPI specification, describing all API endpoints, their methods, responses, and data schemas, which powers interactive documentation like Swagger UI and ReDoc. ```json { "openapi": "3.0.2", "info": { "title": "FastAPI", "version": "0.1.0" }, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": { "application/json": { ... ``` -------------------------------- ### Run FastAPI Application with Uvicorn Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This command line snippet shows how to run the FastAPI application using Uvicorn, a lightning-fast ASGI server. `main:app` refers to the `app` object within the `main.py` file, and `--reload` enables automatic server restart on code changes for development. ```bash uvicorn main:app --reload ``` -------------------------------- ### Run FastAPI Application (Custom Name) with Uvicorn Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This shell command illustrates how to start a FastAPI application using Uvicorn when the application instance has a custom name, such as `my_awesome_api`. The Uvicorn command must explicitly reference this custom name to correctly load the application. ```shell fast →uvicorn main:my_awesome_api --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) restart ↺ ``` -------------------------------- ### Run FastAPI Application (Default Name) with Uvicorn Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This shell command demonstrates how to launch a FastAPI application named `app` located in `main.py` using Uvicorn. The `--reload` flag enables automatic code reloading on file changes during development. ```shell fast →uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) restart ↺ ``` -------------------------------- ### Install Specific Python Package Version (Example 1) Source: https://fastapi.tiangolo.com/em/virtual-environments Illustrates installing a specific version of a package, `harry==1`, using `pip`. This example is part of a scenario demonstrating why global package installations can lead to version conflicts between different projects. ```shell pip install "harry==1" ``` -------------------------------- ### GET / Source: https://fastapi.tiangolo.com/fr/tutorial/cors An example GET endpoint demonstrating a basic FastAPI route within a CORS-configured application. It returns a simple 'Hello World' message. ```APIDOC ## GET / ### Description A simple example endpoint that returns a "Hello World" message. This endpoint is part of the FastAPI application configured with CORSMiddleware. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` GET / ``` ### Response #### Success Response (200) - **message** (string) - A greeting message. #### Response Example ```json { "message": "Hello World" } ``` ``` -------------------------------- ### Define FastAPI Route Operation Function (Synchronous) Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This Python example shows a synchronous route operation function, `def root()`, that handles GET requests for the root path. FastAPI supports both `async def` and regular `def` functions for route handlers, allowing flexibility based on implementation needs. ```python from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return {"message": "Hello World"} ``` -------------------------------- ### FastAPI Root Endpoint JSON Response Source: https://fastapi.tiangolo.com/em/tutorial/first-steps This JSON snippet shows the expected output when a client accesses the root endpoint (e.g., `http://127.0.0.1:8000/`) of the basic FastAPI application. It's a simple key-value pair. ```json {"message": "Hello World"} ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/ja/reference/apirouter Retrieves a list of example items. This endpoint demonstrates a basic GET request using FastAPI. ```APIDOC ## GET /items/\n\n### Description\nRetrieves a list of example items. This endpoint demonstrates a basic GET request using FastAPI.\n\n### Method\nGET\n\n### Endpoint\n/items/\n\n### Parameters\n#### Path Parameters\n(None)\n\n#### Query Parameters\n(None)\n\n#### Request Body\n(None)\n\n### Request Example\n(None)\n\n### Response\n#### Success Response (200)\n- **name** (string) - The name of the item.\n\n#### Response Example\n```json\n[\n {\n "name": "Empanada"\n },\n {\n "name": "Arepa"\n }\n]\n``` ``` -------------------------------- ### Install FastAPI with standard dependencies Source: https://fastapi.tiangolo.com/em This command installs the FastAPI library, including its standard dependencies. It provides the necessary components to start developing FastAPI applications, often encompassing an ASGI server like Uvicorn. ```bash pip install "fastapi[standard]" ``` -------------------------------- ### Serve Built Multilingual FastAPI Documentation (Python CLI) Source: https://fastapi.tiangolo.com/de/contributing This command-line script starts a simple local web server to preview the fully built multilingual FastAPI documentation. It serves the content from the `./site/` directory, which must have been generated by the `build-all` command. It is intended for final previewing rather than active development. ```bash python ./scripts/docs.py serve ``` -------------------------------- ### Install and Run FastAPI CLI in Development Source: https://fastapi.tiangolo.com/fa/release-notes This command-line example demonstrates how to install the FastAPI library using pip and then initiate a development server using the new `fastapi dev` command. The output provides server details, API documentation links, and indicates that file changes are being watched for live reloading. ```bash $ 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. ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/tutorial/path-operation-configuration Retrieves a list of available items. This is a basic example demonstrating a GET request. ```APIDOC ## GET /items/ ### Description Retrieves a list of available items. ### Method GET ### Endpoint /items/ ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (None) ### Response #### Success Response (200 OK) - **name** (string) - The name of the item. - **price** (float) - The price of the item. #### Response Example ```json [ { "name": "Foo", "price": 42 } ] ``` ``` -------------------------------- ### Run FastAPI development server with `fastapi dev` Source: https://fastapi.tiangolo.com/fa/tutorial/first-steps This command initiates the FastAPI development server, typically using `uvicorn` under the hood, to host the application defined in `main.py`. The console output displays server startup information, the local URL for the application and documentation, and indicates that the server is running in development mode with file watching enabled. ```shell fast →fastapi dev _main.py_ FastAPI Starting development server 🚀 Searching for package file structure from directories with __init__.py files Importing from /home/user/code/awesomeapp module 🐍 main.py code Importing the FastAPI app object from the module with the following code: _from __**main**__ import __**app**_ app Using import string: main:app server Server started at _http://127.0.0.1:8000_ server Documentation at _http://127.0.0.1:8000/docs_ tip Running in development mode, for production use: **fastapi run** Logs: 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 **[****383138****]** using WatchFiles INFO Started server process **[****383153****]** INFO Waiting for application startup. INFO Application startup complete. restart ↻ ``` -------------------------------- ### Build Standard FastAPI Docker Image Source: https://fastapi.tiangolo.com/em/deployment/docker This Dockerfile example demonstrates how to build a standard Docker image for a FastAPI application. It uses the `tiangolo/uvicorn-gunicorn-fastapi` base image, copies `requirements.txt`, installs dependencies, and then copies the application code into the `/app` directory. ```Dockerfile FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 COPY ./requirements.txt /app/requirements.txt RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt COPY ./app /app ``` -------------------------------- ### Create a Basic FastAPI App and Run Server (Python) Source: https://fastapi.tiangolo.com/tutorial/first-steps This snippet demonstrates the simplest FastAPI application. It imports the FastAPI class, creates an instance, and defines a root path operation that returns a JSON message. The associated command shows how to run this application using the FastAPI development server. ```python from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} ``` ```bash fastapi dev main.py ``` -------------------------------- ### Install and Run FastAPI CLI in Development Mode Source: https://fastapi.tiangolo.com/uk/release-notes This snippet demonstrates how to install the FastAPI framework and then run a Python application using the new FastAPI CLI in development mode. It showcases the command-line instructions to set up and execute a FastAPI application, including dependency installation via pip. The `fastapi dev` command starts a development server with live reloading. ```bash $ pip install --upgrade fastapi $ fastapi dev main.py ``` -------------------------------- ### Run FastAPI Example Application using Uvicorn Development Server Source: https://fastapi.tiangolo.com/de/contributing This command starts a FastAPI application in development mode using Uvicorn. It specifies the Python file `tutorial001.py` as the entry point. The application will be served on port 8000, avoiding conflicts with the documentation server running on port 8008. ```bash fast →fastapi dev tutorial001.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) restart ↺ ``` -------------------------------- ### Test FastAPI WebSockets and HTTP Endpoints with TestClient Source: https://fastapi.tiangolo.com/fa/advanced/testing-websockets This Python example demonstrates how to use FastAPI's `TestClient` to write integration tests for both standard HTTP GET endpoints and WebSocket endpoints. It includes a minimal FastAPI application setup, a GET route, a WebSocket route, and two test functions showcasing how to interact with these endpoints using the `TestClient`. ```python from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocket app = FastAPI() @app.get("/") async def read_main(): return {"msg": "Hello World"} @app.websocket("/ws") async def websocket(websocket: WebSocket): await websocket.accept() await websocket.send_json({"msg": "Hello WebSocket"}) await websocket.close() def test_read_main(): client = TestClient(app) response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"} def test_websocket(): client = TestClient(app) with client.websocket_connect("/ws") as websocket: data = websocket.receive_json() assert data == {"msg": "Hello WebSocket"} ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/tr/reference/apirouter Retrieves a list of example items from the API. This endpoint demonstrates a basic GET request without any input parameters. ```APIDOC ## GET /items/ ### Description This endpoint retrieves a list of predefined items. It demonstrates a basic GET request in a FastAPI application. ### Method GET ### Endpoint /items/ ### Parameters None. This endpoint does not require any path, query, or request body parameters. ### Request Example {} ### Response #### Success Response (200) - **name** (string) - The name of an item. #### Response Example ```json [ { "name": "Empanada" }, { "name": "Arepa" } ] ``` ``` -------------------------------- ### FastAPI GET Endpoint with Default Header Parameter (Partial) Source: https://fastapi.tiangolo.com/tutorial/testing This partial FastAPI code snippet illustrates an alternative method for defining a required header parameter, `x_token`, by assigning `Header()` as its default value, without using `Annotated`. It includes the same token validation and item retrieval logic for a `GET` endpoint. Note that the `POST` endpoint definition is incomplete in this example. ```python from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"} } app = FastAPI() class Item(BaseModel): id: str title: str description: str | None = None @app.get("/items/{item_id}", response_model=Item) async def read_main(item_id: str, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_id] @app.post("/items/", response_model=Item) ``` -------------------------------- ### Run FastAPI Development Server from Documentation Examples Source: https://fastapi.tiangolo.com/fr/contributing This command demonstrates how to run a FastAPI application directly from a documentation example file using the `fastapi dev` command. The output shows the Uvicorn server starting on port 8000, which by default avoids port clashes with the documentation server (typically on 8008). ```shell fast →fastapi dev tutorial001.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) restart ↻ ``` -------------------------------- ### Serve FastAPI Docs Locally Using MkDocs for a Specific Language Source: https://fastapi.tiangolo.com/fa/contributing These commands provide an alternative, manual method to serve the documentation for a specific language. First, navigate into the target language's documentation directory, then use `mkdocs serve` to start a local development server. This method requires `mkdocs` to be installed and accessible in your environment, providing a live preview at the specified address. ```bash cd docs/es/ ``` ```bash mkdocs serve --dev-addr 127.0.0.1:8008 ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/pt/reference/fastapi Defines an HTTP GET endpoint to retrieve a list of items. This example illustrates a simple GET request returning a static list of items. ```APIDOC ## GET /items/ ### Description Defines an HTTP GET endpoint to retrieve a list of items. ### Method GET ### Endpoint /items/ ### Parameters #### Path Parameters _None_ #### Query Parameters _None_ #### Request Body _None_ ### Request Example _None_ ### Response #### Success Response (200) - **name** (string) - The name of an item. #### Response Example ```json [ { "name": "Empanada" }, { "name": "Arepa" } ] ``` ``` -------------------------------- ### Run FastAPI application using the Uvicorn development server Source: https://fastapi.tiangolo.com/fa/contributing This shell command demonstrates how to run a FastAPI application file, `tutorial001.py`, using the `fastapi dev` command. It initializes Uvicorn, which serves the application on `http://127.0.0.1:8000` by default. This setup allows developers to run documentation examples and ensures port compatibility with the documentation server. ```shell fastapi dev tutorial001.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` -------------------------------- ### Serve compiled FastAPI documentation locally Source: https://fastapi.tiangolo.com/contributing Serves the fully built FastAPI documentation locally for preview. After running `build-all`, the command `python ./scripts/docs.py serve` launches a simple HTTP server, typically accessible at `http://127.0.0.1:8008`. This allows developers to review the combined, multi-language documentation as it would appear online. ```bash python ./scripts/docs.py serve ``` -------------------------------- ### Manually Serve FastAPI Docs Live for Existing Language (Bash & MkDocs) Source: https://fastapi.tiangolo.com/ko/contributing As an alternative to the script, these commands manually set up and serve the FastAPI documentation for a specific language. First, change the directory to the language's documentation folder (e.g., `docs/es/`), then run `mkdocs serve` to start the local development server. ```bash cd docs/es/ ``` ```bash mkdocs serve --dev-addr 127.0.0.1:8008 ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/fr/reference/fastapi Defines an API endpoint for an HTTP GET request to retrieve a list of items. This example demonstrates a basic GET operation without any path or query parameters. ```APIDOC ## GET /items/ ### Description Retrieves a list of sample items (Empanada, Arepa). ### Method GET ### Endpoint /items/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example GET requests typically do not have a request body. ### Response #### Success Response (200) - **array** (list of objects) - A list of item objects. #### Response Example ```json [ { "name": "Empanada" }, { "name": "Arepa" } ] ``` ``` -------------------------------- ### GET /items/ (Example with Depends) Source: https://fastapi.tiangolo.com/ru/reference/dependencies Example API endpoint demonstrating how to use `fastapi.Depends` to inject common query parameters into a path operation. ```APIDOC ## GET /items/ ### Description Retrieves a list of items with optional filtering, skipping, and limiting. This endpoint showcases the use of `fastapi.Depends` to manage common query parameters for reusability. ### Method GET ### Endpoint /items/ ### Parameters #### Query Parameters - **q** (str) - Optional - A search query string for filtering items. - **skip** (int) - Optional - The number of items to skip from the beginning of the list. Default: 0. - **limit** (int) - Optional - The maximum number of items to return in the response. Default: 100. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **q** (str) - The query string used for filtering. - **skip** (int) - The number of skipped items. - **limit** (int) - The maximum number of returned items. #### Response Example ```json { "q": "example_query_string", "skip": 0, "limit": 100 } ``` ``` -------------------------------- ### Serve FastAPI Documentation Live Using Python Script Source: https://fastapi.tiangolo.com/ru/contributing Use this Python script to build and serve the FastAPI documentation locally. It enables live-reloading, allowing you to see changes instantly as you edit documentation or source files. The documentation will be available at `http://127.0.0.1:8008`. ```bash python ./scripts/docs.py live ``` -------------------------------- ### GET /users/ Source: https://fastapi.tiangolo.com/vi/tutorial/path-operation-configuration Retrieves a list of users. This endpoint is part of an example demonstrating basic GET requests. ```APIDOC ## GET /users/ ### Description Retrieves a list of users. ### Method GET ### Endpoint /users/ ### Parameters None ### Request Example None ### Response #### Success Response (200) - **username** (string) - The username. #### Response Example ```json [ { "username": "johndoe" } ] ``` ``` -------------------------------- ### GET /status/ - Get System Status Source: https://fastapi.tiangolo.com/zh/advanced/security/oauth2-scopes Checks and returns the current operational status of the system. Requires authentication. ```APIDOC ## GET /status/ ### Description Provides a simple check for the system's operational status. This endpoint requires a valid access token for authentication, but no specific scopes are enforced beyond general user authentication. ### Method GET ### Endpoint /status/ ### Parameters #### Request Headers - **Authorization** (string) - Required - Bearer token (e.g., `Bearer `). ### Request Example ``` GET /status/ Authorization: Bearer ``` ### Response #### Success Response (200) - **status** (string) - A string indicating the system's health, typically "ok". #### Error Response (401) - **detail** (string) - "Could not validate credentials" ### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/ru/reference/fastapi Retrieves a list of predefined items. This example illustrates a simple GET path operation in FastAPI. ```APIDOC ## GET /items/ ### Description Retrieves a list of predefined items. This example illustrates a simple GET path operation in FastAPI. ### Method GET ### Endpoint /items/ ### Request Example (No request body for this GET endpoint) ### Response #### Success Response (200) - **name** (string) - The name of the item. #### Response Example ```json [ { "name": "Empanada" }, { "name": "Arepa" } ] ``` ``` -------------------------------- ### Install Specific Python Package Version (Example 2) Source: https://fastapi.tiangolo.com/em/virtual-environments Shows installing another specific version of the `harry` package, `harry==3`, using `pip`. This command, following an installation of `harry==1`, highlights the problem of managing conflicting dependencies in a global Python environment. ```shell pip install "harry==3" ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/reference/apirouter Retrieves a list of predefined items. This example demonstrates a basic GET request with a hardcoded response. ```APIDOC ## GET /items/ ### Description Retrieves a list of predefined items from the server. This endpoint serves as a basic example of a GET request in FastAPI, returning a static array of item objects. ### Method GET ### Endpoint /items/ ### Parameters (None) ### Request Example (No request body) ### Response #### Success Response (200) - **array of objects** - A list containing item objects. - **name** (string) - The name of the item. #### Response Example ```json [ { "name": "Empanada" }, { "name": "Arepa" } ] ``` ``` -------------------------------- ### Run FastAPI Application with Uvicorn Development Server Source: https://fastapi.tiangolo.com/advanced/websockets This command demonstrates how to start the FastAPI application using the `fastapi dev` command, which internally uses Uvicorn. It specifies `main.py` as the application entry point, enabling automatic reloading during development. The server will be accessible at `http://127.0.0.1:8000`. ```shell fast →fastapi dev main.py ``` -------------------------------- ### FastAPI Application Setup and Imports (Python) Source: https://fastapi.tiangolo.com/de/advanced/websockets Initializes the FastAPI application and imports necessary modules for handling HTTP responses, WebSockets, cookies, query parameters, and dependency injection. This sets up the core framework for the server-side logic. ```python from typing import Union from fastapi import ( Cookie, Depends, FastAPI, Query, WebSocket, WebSocketException, status, ) from fastapi.responses import HTMLResponse app = FastAPI() ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/vi/reference/apirouter Defines an API endpoint that handles HTTP GET requests to retrieve a collection of items. This example demonstrates a simple GET operation without any request parameters. ```APIDOC ## GET /items/ ### Description Retrieves a list of items from the server. This endpoint does not require any request parameters. ### Method GET ### Endpoint /items/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example {} ### Response #### Success Response (200) - **(array)** - A list of item objects. - **name** (string) - The name of the item. #### Response Example [ { "name": "Empanada" }, { "name": "Arepa" } ] ``` -------------------------------- ### GET /status/ - Get System Status Source: https://fastapi.tiangolo.com/zh/advanced/security/oauth2-scopes Checks the system status. Requires basic authentication to ensure the user exists. ```APIDOC ## GET /status/ ### Description This endpoint provides a basic system status check. It requires any authenticated user to access, though no specific scopes are enforced beyond successful authentication. ### Method GET ### Endpoint /status/ ### Parameters #### Request Headers - **Authorization** (string) - Required - Bearer token (e.g., `Bearer `) ### Request Example (No request body) ### Response #### Success Response (200) - **status** (string) - A simple status message. - **user** (string) - The username of the authenticated user. #### Response Example ```json { "status": "System Operational", "user": "johndoe" } ``` #### Error Response (401) - **detail** (string) - Error message, e.g., "Could not validate credentials". #### Error Example ```json { "detail": "Could not validate credentials" } ``` ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/fr/reference/apirouter Defines a path operation for retrieving a list of items using an HTTP GET request. This example demonstrates a basic GET endpoint returning static data. ```APIDOC ## GET /items/ ### Description Retrieves a list of predefined items. This endpoint is defined using FastAPI's `@router.get()` decorator. ### Method GET ### Endpoint /items/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **name** (string) - The name of an item. #### Response Example ```json [ { "name": "Empanada" }, { "name": "Arepa" } ] ``` ``` -------------------------------- ### Run Traefik Proxy with Custom Configuration Source: https://fastapi.tiangolo.com/fa/advanced/behind-a-proxy This command demonstrates how to start the Traefik proxy using a specific configuration file (`traefik.toml`). It initializes Traefik to listen for incoming requests and apply the defined routing and middleware rules. ```bash fast →./traefik --configFile=traefik.toml INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml restart ↻ ``` -------------------------------- ### Serve FastAPI Documentation Manually with mkdocs Source: https://fastapi.tiangolo.com/ko/contributing As an alternative to the Python script, you can manually serve the documentation by navigating to the language-specific docs directory (e.g., `docs/en/`) and running `mkdocs serve`. This command starts a local server to display the documentation at the specified address. ```bash cd docs/en/ mkdocs serve --dev-addr 127.0.0.1:8008 ``` -------------------------------- ### GET /items/ (Initial Example) Source: https://fastapi.tiangolo.com/tr/tutorial/path-operation-configuration Retrieve a list of items. This endpoint demonstrates a basic GET operation returning a predefined list of item objects with name and price. ```APIDOC ## GET /items/ ### Description Retrieve a list of items. This endpoint demonstrates a basic GET operation returning a predefined list of item objects with name and price. ### Method GET ### Endpoint /items/ ### Parameters #### Path Parameters _None_ #### Query Parameters _None_ #### Request Body _None_ ### Request Example _None_ ### Response #### Success Response (200) - **name** (string) - The name of an item. - **price** (number) - The price of an item. #### Response Example ```json [ { "name": "Foo", "price": 42 } ] ``` ``` -------------------------------- ### GET /items/ Source: https://fastapi.tiangolo.com/vi/tutorial/path-operation-configuration Retrieves a list of available items. This endpoint is part of an example demonstrating basic GET requests. ```APIDOC ## GET /items/ ### Description Retrieves a list of available items. ### Method GET ### Endpoint /items/ ### Parameters None ### Request Example None ### Response #### Success Response (200) - **name** (string) - The name of the item. - **price** (float) - The price of the item. #### Response Example ```json [ { "name": "Foo", "price": 42 } ] ``` ``` -------------------------------- ### GET /users/ Source: https://fastapi.tiangolo.com/zh/reference/apirouter Retrieves a list of example user data from the application. ```APIDOC ## GET /users/ ### Description Retrieves a list of user objects, each containing a name. This endpoint is defined within a `users_router` and is accessible through the main application via an `internal_router`. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters - No path parameters. #### Query Parameters - No query parameters. #### Request Body - No request body. ### Request Example No request body is required for this endpoint. ### Response #### Success Response (200) - **name** (string) - The name of the user. #### Response Example ```json [ { "name": "Rick" }, { "name": "Morty" } ] ``` ``` -------------------------------- ### FastAPI Protected Endpoint to Read System Status Source: https://fastapi.tiangolo.com/zh/advanced/security/oauth2-scopes This GET endpoint (`/status/`) provides an example of a simple protected route that only requires -------------------------------- ### GET /users/ Source: https://fastapi.tiangolo.com/tutorial/path-operation-configuration Retrieves a list of registered users. This is a basic example demonstrating a GET request for user data. ```APIDOC ## GET /users/ ### Description Retrieves a list of registered users. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (None) ### Response #### Success Response (200 OK) - **username** (string) - The username of the user. #### Response Example ```json [ { "username": "johndoe" } ] ``` ``` -------------------------------- ### POST /users/ Source: https://fastapi.tiangolo.com/fr/advanced/generate-clients Creates a new user with a username and email, demonstrating another POST operation. ```APIDOC ## POST /users/ ### Description Creates a new user with a username and email. ### Method POST ### Endpoint /users/ ### Parameters #### Request Body - **username** (string) - Required - The username of the new user. - **email** (string) - Required - The email address of the new user. ### Request Example { "username": "john_doe", "email": "john.doe@example.com" } ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the user was received. #### Response Example { "message": "User received" } ``` -------------------------------- ### GET / Source: https://fastapi.tiangolo.com/fr/advanced/websockets This endpoint serves the main HTML page for the WebSocket chat application. It's a standard GET request that returns static HTML content. ```APIDOC ## GET / ### Description This endpoint serves the main HTML page for the WebSocket chat application. It provides the front-end interface for users to connect to the WebSocket and send messages. ### Method GET ### Endpoint / ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) Returns an HTML page for the chat application. #### Response Example ```html Chat

WebSocket Chat


``` ``` -------------------------------- ### Serve MkDocs Manually for a Specific Language (Shell) Source: https://fastapi.tiangolo.com/ja/contributing Manually start the MkDocs development server from within a language's directory. This serves the documentation locally, typically on port 8008, allowing you to preview translated content. ```bash mkdocs serve --dev-addr 127.0.0.1:8008 ``` -------------------------------- ### FastAPI JWT Authentication Setup: Constants, Models, and Dependencies Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Defines all necessary imports, security constants (SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES), a mock user database, Pydantic models for request/response bodies and internal user representation, and initializes FastAPI security components and the app instance. ```python from datetime import datetime, timedelta, timezone from typing import Annotated, Union import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jwt.exceptions import InvalidTokenError from pwdlib import PasswordHash from pydantic import BaseModel SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } class Token(BaseModel): access_token: str token_type: str class TokenData(BaseModel): username: Union[str, None] = None class User(BaseModel): username: str email: Union[str, None] = None full_name: Union[str, None] = None disabled: Union[bool, None] = None class UserInDB(User): hashed_password: str password_hash = PasswordHash.recommended() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") app = FastAPI() ``` -------------------------------- ### FastAPI Endpoints with Annotated Header and Error Handling Source: https://fastapi.tiangolo.com/tutorial/testing This FastAPI application defines `GET` and `POST` endpoints that require an `X-Token` header, validated using `Annotated`. It handles common errors like invalid tokens, non-existent items for GET requests, and conflicts for POST requests by raising `HTTPException`. The example includes variations for Python 3.10+ (`str | None`) and Python 3.9/3.8 (`Union[str, None]` with or without `typing_extensions.Annotated`) for Pydantic model type hints. ```python from typing import Annotated from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"} } app = FastAPI() class Item(BaseModel): id: str title: str description: str | None = None @app.get("/items/{item_id}", response_model=Item) async def read_main(item_id: str, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_id] @app.post("/items/", response_model=Item) async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item ``` ```python from typing import Annotated, Union from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"} } app = FastAPI() class Item(BaseModel): id: str title: str description: Union[str, None] = None @app.get("/items/{item_id}", response_model=Item) async def read_main(item_id: str, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_id] @app.post("/items/", response_model=Item) async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item ``` ```python from typing import Union from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel from typing_extensions import Annotated fake_secret_token = "coneofsilence" fake_db = { "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"}, "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"} } app = FastAPI() class Item(BaseModel): id: str title: str description: Union[str, None] = None @app.get("/items/{item_id}", response_model=Item) async def read_main(item_id: str, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: raise HTTPException(status_code=404, detail="Item not found") return fake_db[item_id] @app.post("/items/", response_model=Item) async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item ``` -------------------------------- ### GET /users/me/items/ - Get User's Items Source: https://fastapi.tiangolo.com/tr/tutorial/security/oauth2-jwt Retrieves a list of items owned by the currently authenticated and active user. This is an example of accessing a protected resource. ```APIDOC ## GET /users/me/items/ ### Description Fetches a list of items belonging to the current active user. This endpoint demonstrates accessing a resource protected by authentication. ### Method GET ### Endpoint /users/me/items/ ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token received from the /token endpoint. ### Request Example No request body. ``` Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` ### Response #### Success Response (200 OK) - **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 Unauthorized) - If no token is provided or the token is invalid. #### Response Example (401) ```json { "detail": "Could not validate credentials" } ``` #### Error Response (400 Bad Request) - If the authenticated user is disabled. #### Response Example (400) ```json { "detail": "Inactive user" } ``` ``` -------------------------------- ### POST /items/ Source: https://fastapi.tiangolo.com/fr/advanced/generate-clients Creates a new item with a name and price, demonstrating a POST operation. ```APIDOC ## POST /items/ ### Description Creates a new item with a name and price. ### Method POST ### Endpoint /items/ ### Parameters #### Request Body - **name** (string) - Required - The name of the item. - **price** (number) - Required - The price of the item. ### Request Example { "name": "New Item", "price": 10.99 } ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the item was received. #### Response Example { "message": "Item received" } ``` -------------------------------- ### Serve FastAPI Docs Live for Existing Language (Python) Source: https://fastapi.tiangolo.com/em/contributing This command uses a Python script to start a local development server for FastAPI documentation. It allows previewing translated content for an existing language, specified by its two-letter code (e.g., 'es'). The server runs on http://127.0.0.1:8008 and watches for file changes. ```python python ./scripts/docs.py live es ```