### Run FastAPI Development Server Source: https://fastapi.tiangolo.com/tutorial To run any of the examples, copy the code to a file `main.py`, and start `fastapi dev`. It is highly encouraged to write or copy the code, edit it and run it locally. ```bash fastapi dev fast → ``` -------------------------------- ### Install FastAPI with Standard Dependencies Source: https://fastapi.tiangolo.com/tutorial Install FastAPI with optional standard dependencies, including `fastapi-cloud-cli`. Alternatively, install `pip install fastapi` for a minimal setup or `pip install "fastapi[standard-no-fastapi-cloud-cli]"` to exclude the CLI. ```bash pip install "fastapi[standard]" fast →pip install "fastapi[standard]" restart ↻ ``` -------------------------------- ### Install httpx Source: https://fastapi.tiangolo.com/tutorial/testing To use TestClient, you need to install the httpx library. Ensure you have a virtual environment activated before installation. ```bash $ pip install httpx ``` -------------------------------- ### Install python-multipart Source: https://fastapi.tiangolo.com/tutorial/request-form-models Install the python-multipart library to enable form data handling in FastAPI. ```bash $ pip install python-multipart ``` -------------------------------- ### Install SQLModel Source: https://fastapi.tiangolo.com/tutorial/sql-databases Install the SQLModel library using pip. Ensure your virtual environment is activated before running the command. ```bash pip install sqlmodel fast →pip install sqlmodel restart ↻ ``` -------------------------------- ### Install Pytest Source: https://fastapi.tiangolo.com/tutorial/testing Install pytest using pip. Ensure you are in a virtual environment. ```bash pip install pytest ``` -------------------------------- ### Example URL for Multiple Query Parameters Source: https://fastapi.tiangolo.com/tutorial/query-params-str-validations Demonstrates how multiple query parameters with the same name are structured in a URL. ```text http://localhost:8000/items/?q=foo&q=bar ``` -------------------------------- ### File Structure Example Source: https://fastapi.tiangolo.com/tutorial/bigger-applications Illustrates a typical file structure for a FastAPI application, highlighting Python packages and modules. ```text . ├── app │ ├── __init__.py │ ├── main.py │ ├── dependencies.py │ └── routers │ │ ├── __init__.py │ │ ├── items.py │ │ └── users.py │ └── internal │ ├── __init__.py │ └── admin.py ``` -------------------------------- ### Create Database Tables on Startup Source: https://fastapi.tiangolo.com/tutorial/sql-databases This snippet shows how to create the necessary database tables when the FastAPI application starts up. ```python app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() ``` -------------------------------- ### Protected Endpoint: Get User Items Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt An example endpoint demonstrating how to access user-specific data after authentication. It returns a list of items owned by the current active user. ```python @app.get("/users/me/items/") async def read_own_items(current_user: User = Depends(get_current_active_user)): return [{"item_id": "Foo", "owner": current_user.username}] ``` -------------------------------- ### Annotated Body with Multiple Examples Source: https://fastapi.tiangolo.com/tutorial/schema-extra-example Demonstrates passing multiple examples for a request body using Annotated and Body(). These examples can be used to showcase different valid inputs. ```Python from typing import Annotated from fastapi import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Annotated[ Item, Body( examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, { "name": "Bar", "price": "35.4", }, { "name": "Baz", "price": "thirty five point four", }, ], ), ], ): results = {"item_id": item_id, "item": item} return results ``` -------------------------------- ### Install pwdlib with Argon2 Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Install the pwdlib package with Argon2 support. This command should be run within an activated virtual environment. ```bash pip install "pwdlib[argon2]" ``` -------------------------------- ### Define a Root Endpoint with a Synchronous Function Source: https://fastapi.tiangolo.com/tutorial/first-steps This example demonstrates defining a GET operation for the root path ('/') using a standard synchronous function instead of an async function. ```python from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return {"message": "Hello World"} ``` -------------------------------- ### Non-Annotated Body with Multiple Examples Source: https://fastapi.tiangolo.com/tutorial/schema-extra-example Shows how to pass multiple examples for a request body without using Annotated. This provides flexibility in defining example request data. ```Python from fastapi import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Item = Body( examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, { "name": "Bar", "price": "35.4", }, { "name": "Baz", "price": "thirty five point four", }, ], ), ): results = {"item_id": item_id, "item": item} return results ``` -------------------------------- ### Example URL for Default List Query Parameter Source: https://fastapi.tiangolo.com/tutorial/query-params-str-validations Demonstrates accessing the endpoint with no query parameters to receive the default list value. ```text http://localhost:8000/items/ ``` -------------------------------- ### Example User Data Response Source: https://fastapi.tiangolo.com/tutorial/security/simple-oauth2 This is an example of the JSON response received when successfully retrieving user data after authentication. ```json { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false, "hashed_password": "fakehashedsecret" } ``` -------------------------------- ### Annotated Body with Single Example Source: https://fastapi.tiangolo.com/tutorial/schema-extra-example Shows how to pass a single example for a request body using Annotated and Body(). This example is added to the JSON Schema and OpenAPI documentation. ```Python from typing import Annotated from fastapi import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( item_id: int, item: Annotated[ Item, Body( examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, } ], ), ], ): results = {"item_id": item_id, "item": item} return results ``` -------------------------------- ### Update Item with OpenAPI Examples (Annotated) Source: https://fastapi.tiangolo.com/tutorial/schema-extra-example Demonstrates how to define multiple OpenAPI examples for a request body using `Annotated` and `Body`. This is useful for showcasing different valid and invalid input scenarios in API documentation. ```python from typing import Annotated from fastapi import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Annotated[ Item, Body( openapi_examples={ "normal": { "summary": "A normal example", "description": "A **normal** item works correctly.", "value": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, }, "converted": { "summary": "An example with converted data", "description": "FastAPI can convert price `strings` to actual `numbers` automatically", "value": { "name": "Bar", "price": "35.4", }, }, "invalid": { "summary": "Invalid data is rejected with an error", "value": { "name": "Baz", "price": "thirty five point four", }, }, }, ), ], ): results = {"item_id": item_id, "item": item} return results ``` -------------------------------- ### Full Example with Annotated Shortcut Dependency Source: https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies Demonstrates the full implementation of a FastAPI application using the Annotated shortcut for class-based dependencies. Requires Python 3.10+. ```python from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI() fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] class CommonQueryParams: def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100): self.q = q self.skip = skip self.limit = limit @app.get("/items/") async def read_items(commons: Annotated[CommonQueryParams, Depends()]): response = {} if commons.q: response.update({"q": commons.q}) items = fake_items_db[commons.skip : commons.skip + commons.limit] response.update({"items": items}) return response ``` -------------------------------- ### Install PyJWT Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Install the PyJWT library to handle JWT token generation and verification in Python. For advanced algorithms like RSA or ECDSA, install with crypto support. ```bash pip install pyjwt ``` -------------------------------- ### Define Hero Model and Database Setup Source: https://fastapi.tiangolo.com/tutorial/sql-databases Defines the Hero SQLModel and sets up the SQLite database engine and session dependency. ```python from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class Hero(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) age: int | None = Field(default=None, index=True) secret_name: str sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_session)] app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() ``` -------------------------------- ### URL for Required Query Parameter Source: https://fastapi.tiangolo.com/tutorial/query-params Example of how to construct a URL with a required query parameter. ```text http://127.0.0.1:8000/items/foo-item?needy=sooooneedy ``` -------------------------------- ### Full Example with Non-Annotated Shortcut Dependency Source: https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies Demonstrates the full implementation of a FastAPI application using the non-Annotated shortcut for class-based dependencies. Requires Python 3.10+. ```python from fastapi import Depends, FastAPI app = FastAPI() fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] class CommonQueryParams: def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100): self.q = q self.skip = skip self.limit = limit @app.get("/items/") async def read_items(commons: CommonQueryParams = Depends()): response = {} if commons.q: response.update({"q": commons.q}) items = fake_items_db[commons.skip : commons.skip + commons.limit] response.update({"items": items}) return response ``` -------------------------------- ### Pydantic Model Field with Examples Source: https://fastapi.tiangolo.com/tutorial/schema-extra-example Demonstrates declaring additional examples for Pydantic model fields using Field(). These examples are used for documentation and validation. ```Python from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str = Field(examples=["Foo"]) description: str | None = Field(default=None, examples=["A very nice Item"]) price: float = Field(examples=[35.4]) tax: float | None = Field(default=None, examples=[3.2]) @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results ``` -------------------------------- ### Run FastAPI Development Server Source: https://fastapi.tiangolo.com/tutorial/sql-databases Use this command to start the FastAPI development server. It automatically reloads the application on code changes. ```bash fastapi dev ``` -------------------------------- ### Password Hashing with bcrypt Source: https://fastapi.tiangolo.com/tutorial/security/simple-oauth2 Implement password hashing using bcrypt for secure storage and verification. This example demonstrates how to hash a password and verify it against a stored hash. ```python import bcrypt password = b"supersecretpassword" # Hash the password hashed_password = bcrypt.hashpw(password, bcrypt.gensalt()) # Verify the password if bcrypt.checkpw(password, hashed_password): print("Password is correct!") else: print("Password is incorrect!") ``` -------------------------------- ### Sub-dependencies with yield (Annotated) Source: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield Demonstrates a chain of sub-dependencies where each uses `yield` for setup and teardown. FastAPI ensures correct execution order for both yield and finally blocks. ```python from typing import Annotated from fastapi import Depends async def dependency_a(): dep_a = generate_dep_a() try: yield dep_a finally: dep_a.close() async def dependency_b(dep_a: Annotated[DepA, Depends(dependency_a)]): dep_b = generate_dep_b() try: yield dep_b finally: dep_b.close(dep_a) async def dependency_c(dep_b: Annotated[DepB, Depends(dependency_b)]): dep_c = generate_dep_c() try: yield dep_c finally: dep_c.close(dep_b) ``` -------------------------------- ### Update Item with OpenAPI Examples (Non-Annotated) Source: https://fastapi.tiangolo.com/tutorial/schema-extra-example Provides an alternative way to define OpenAPI examples for a request body without using `Annotated`. This approach is functionally equivalent to the `Annotated` version for defining examples. ```python from fastapi import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Item = Body( openapi_examples={ "normal": { "summary": "A normal example", "description": "A **normal** item works correctly.", "value": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, }, "converted": { "summary": "An example with converted data", "description": "FastAPI can convert price `strings` to actual `numbers` automatically", "value": { "name": "Bar", "price": "35.4", }, }, "invalid": { "summary": "Invalid data is rejected with an error", "value": { "name": "Baz", "price": "thirty five point four", }, }, }, ), ): results = {"item_id": item_id, "item": item} return results ``` -------------------------------- ### Non-Annotated Body with Single Example Source: https://fastapi.tiangolo.com/tutorial/schema-extra-example Provides an alternative way to pass a single example for a request body without using Annotated. This is useful for older Python versions or simpler cases. ```Python from fastapi import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( item_id: int, item: Item = Body( examples=[ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, } ], ), ): results = {"item_id": item_id, "item": item} return results ``` -------------------------------- ### Define Mixed Query Parameters in FastAPI Source: https://fastapi.tiangolo.com/tutorial/query-params Example demonstrating how to define a mix of required, default, and optional query parameters in a single route. ```python from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_user_item( item_id: str, needy: str, skip: int = 0, limit: int | None = None ): item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit} return item ``` -------------------------------- ### Example User Response Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt This is the typical JSON response received when accessing a protected user endpoint after successful authentication. ```json { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false } ``` -------------------------------- ### Custom Context Manager for Database Session Source: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield Illustrates creating a custom Python context manager class for managing a database session, including setup and teardown logic. ```python class MySuperContextManager: def __init__(self): self.db = DBSession() def __enter__(self): return self.db def __exit__(self, exc_type, exc_value, traceback): self.db.close() ``` -------------------------------- ### FastAPI CRUD Operations with SQLModel and Annotated Source: https://fastapi.tiangolo.com/tutorial/sql-databases Full example of CRUD operations for heroes using SQLModel with Annotated types for dependency injection. This is the recommended approach. ```python from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class HeroBase(SQLModel): name: str = Field(index=True) age: int | None = Field(default=None, index=True) class Hero(HeroBase, table=True): id: int | None = Field(default=None, primary_key=True) secret_name: str class HeroPublic(HeroBase): id: int class HeroCreate(HeroBase): secret_name: str class HeroUpdate(HeroBase): name: str | None = None age: int | None = None secret_name: str | None = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_session)] app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/", response_model=HeroPublic) def create_hero(hero: HeroCreate, session: SessionDep): db_hero = Hero.model_validate(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero @app.get("/heroes/", response_model=list[HeroPublic]) def read_heroes( session: SessionDep, offset: int = 0, limit: Annotated[int, Query(le=100)] = 100, ): heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() return heroes @app.get("/heroes/{hero_id}", response_model=HeroPublic) def read_hero(hero_id: int, session: SessionDep): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") return hero @app.patch("/heroes/{hero_id}", response_model=HeroPublic) def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): hero_db = session.get(Hero, hero_id) if not hero_db: raise HTTPException(status_code=404, detail="Hero not found") hero_data = hero.model_dump(exclude_unset=True) hero_db.sqlmodel_update(hero_data) session.add(hero_db) session.commit() session.refresh(db_hero) return db_hero @app.delete("/heroes/{hero_id}") def delete_hero(hero_id: int, session: SessionDep): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") session.delete(hero) session.commit() return {"ok": True} ``` -------------------------------- ### FastAPI with SQLModel and Annotated Dependencies Source: https://fastapi.tiangolo.com/tutorial/sql-databases Full example of a FastAPI application using SQLModel for database operations with Annotated dependencies for session management. Includes CRUD operations for heroes. ```python from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class HeroBase(SQLModel): name: str = Field(index=True) age: int | None = Field(default=None, index=True) class Hero(HeroBase, table=True): id: int | None = Field(default=None, primary_key=True) secret_name: str class HeroPublic(HeroBase): id: int class HeroCreate(HeroBase): secret_name: str class HeroUpdate(HeroBase): name: str | None = None age: int | None = None secret_name: str | None = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_session)] app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/", response_model=HeroPublic) def create_hero(hero: HeroCreate, session: SessionDep): db_hero = Hero.model_validate(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero @app.get("/heroes/", response_model=list[HeroPublic]) def read_heroes( session: SessionDep, offset: int = 0, limit: Annotated[int, Query(le=100)] = 100, ): heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() return heroes @app.get("/heroes/{hero_id}", response_model=HeroPublic) def read_hero(hero_id: int, session: SessionDep): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") return hero @app.patch("/heroes/{hero_id}", response_model=HeroPublic) def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): hero_db = session.get(Hero, hero_id) if not hero_db: raise HTTPException(status_code=404, detail="Hero not found") hero_data = hero.model_dump(exclude_unset=True) hero_db.sqlmodel_update(hero_data) session.add(hero_db) session.commit() session.refresh(db_hero) return db_hero @app.delete("/heroes/{hero_id}") def delete_hero(hero_id: int, session: SessionDep): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") session.delete(hero) session.commit() return {"ok": True} ``` -------------------------------- ### FastAPI with SQLModel and Standard Dependencies Source: https://fastapi.tiangolo.com/tutorial/sql-databases Alternative example of a FastAPI application using SQLModel without Annotated dependencies. This version uses standard dependency injection for session management. ```python from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class HeroBase(SQLModel): name: str = Field(index=True) age: int | None = Field(default=None, index=True) class Hero(HeroBase, table=True): id: int | None = Field(default=None, primary_key=True) secret_name: str class HeroPublic(HeroBase): id: int class HeroCreate(HeroBase): secret_name: str class HeroUpdate(HeroBase): name: str | None = None age: int | None = None secret_name: str | None = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/", response_model=HeroPublic) def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): db_hero = Hero.model_validate(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero @app.get("/heroes/", response_model=list[HeroPublic]) def read_heroes( session: Session = Depends(get_session), offset: int = 0, limit: int = Query(default=100, le=100), ): heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() return heroes @app.get("/heroes/{hero_id}", response_model=HeroPublic) def read_hero(hero_id: int, session: Session = Depends(get_session)): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") return hero @app.patch("/heroes/{hero_id}", response_model=HeroPublic) def update_hero( hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) ): hero_db = session.get(Hero, hero_id) if not hero_db: raise HTTPException(status_code=404, detail="Hero not found") hero_data = hero.model_dump(exclude_unset=True) hero_db.sqlmodel_update(hero_data) session.add(hero_db) session.commit() ``` -------------------------------- ### FastAPI Router with Relative Imports and Dependencies Source: https://fastapi.tiangolo.com/tutorial/bigger-applications This snippet shows a FastAPI APIRouter setup in `app/routers/items.py` that uses a relative import to access `get_token_header` from `app/dependencies.py`. It defines a router with a prefix, tags, and a dependency, along with example GET and PUT path operations. ```Python from fastapi import APIRouter, Depends, HTTPException from ..dependencies import get_token_header router = APIRouter( prefix="/items", tags=["items"], dependencies=[Depends(get_token_header)], responses={404: {"description": "Not found"}}, ) fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}} @router.get("/") async def read_items(): return fake_items_db @router.get("/{item_id}") async def read_item(item_id: str): if item_id not in fake_items_db: raise HTTPException(status_code=404, detail="Item not found") return {"name": fake_items_db[item_id]["name"], "item_id": item_id} @router.put( "/{item_id}", tags=["custom"], responses={403: {"description": "Operation forbidden"}}, ) async def update_item(item_id: str): if item_id != "plumbus": raise HTTPException( status_code=403, detail="You can only update the item: plumbus" ) return {"item_id": item_id, "name": "The great Plumbus"} ``` -------------------------------- ### Python Module Import Example Source: https://fastapi.tiangolo.com/tutorial/debugging Demonstrates how importing a module prevents the `if __name__ == "__main__":` block from executing. This is the standard behavior when importing Python files. ```python from myapp import app # Some more code ``` -------------------------------- ### Get User from Database Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Retrieves user information from a database (or dictionary in this example) based on the username. Returns a UserInDB object if found. ```python def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) ``` -------------------------------- ### Protected Endpoint: Get Current User Profile Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt An example endpoint that requires authentication. It returns the profile of the currently authenticated and active user. ```python @app.get("/users/me/") async def read_users_me(current_user: User = Depends(get_current_active_user)) -> User: return current_user ``` -------------------------------- ### Create and Use APIRouter Source: https://fastapi.tiangolo.com/tutorial/bigger-applications Demonstrates how to import APIRouter, create an instance, and define path operations for a specific module (e.g., users). ```python from fastapi import APIRouter router = APIRouter() @router.get("/users/", tags=["users"]) async def read_users(): return [{"username": "Rick"}, {"username": "Morty"}] @router.get("/users/me", tags=["users"]) async def read_user_me(): return {"username": "fakecurrentuser"} @router.get("/users/{username}", tags=["users"]) async def read_user(username: str): return {"username": username} ``` -------------------------------- ### Declare Cookies with a Pydantic Model using Annotated Source: https://fastapi.tiangolo.com/tutorial/cookie-param-models Use a Pydantic model to declare multiple cookie parameters. This example uses Annotated for type hinting, which is the preferred method. Ensure you have FastAPI and Pydantic installed. ```python from typing import Annotated from fastapi import Cookie, FastAPI from pydantic import BaseModel app = FastAPI() class Cookies(BaseModel): session_id: str fatebook_tracker: str | None = None googall_tracker: str | None = None @app.get("/items/") async def read_items(cookies: Annotated[Cookies, Cookie()]): return cookies ``` -------------------------------- ### Initialize FastAPI and OAuth2 Scheme Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Set up the FastAPI application instance and the OAuth2 password flow scheme. ```python oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") app = FastAPI() ``` -------------------------------- ### Run FastAPI Development Server with Specific File Source: https://fastapi.tiangolo.com/tutorial/bigger-applications Alternative command to start the FastAPI development server by directly specifying the main Python file. This is less recommended than using pyproject.toml. ```bash $ fastapi dev app/main.py ``` -------------------------------- ### Define Hero Model and Database Setup (without Annotated) Source: https://fastapi.tiangolo.com/tutorial/sql-databases Defines the Hero SQLModel and sets up the SQLite database engine and session dependency, using traditional dependency injection without Annotated. ```python from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Session, SQLModel, create_engine, select class Hero(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) age: int | None = Field(default=None, index=True) secret_name: str sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() ``` -------------------------------- ### Run FastAPI app with --entrypoint option Source: https://fastapi.tiangolo.com/tutorial/first-steps Use the 'fastapi dev' command with the '--entrypoint' option to explicitly specify the module and app instance. This is an alternative to configuring pyproject.toml. ```bash $ fastapi dev --entrypoint main:app ``` -------------------------------- ### Install email-validator for EmailStr Source: https://fastapi.tiangolo.com/tutorial/response-model Instructions for installing the `email-validator` package, which is required for using the `EmailStr` type in Pydantic models. ```bash $ pip install email-validator ``` ```bash $ pip install "pydantic[email]" ``` -------------------------------- ### Example Invalid JSON Payload Source: https://fastapi.tiangolo.com/tutorial/handling-errors This is an example of a JSON payload that would trigger a RequestValidationError due to an incorrect type for the 'size' field. ```json { "title": "towel", "size": "XL" } ``` -------------------------------- ### Password Hashing and Verification Example Source: https://fastapi.tiangolo.com/tutorial/security/simple-oauth2 Illustrates the process of hashing a user's password and comparing it against a stored hash during login. This is crucial for security to avoid storing plain text passwords. ```python hashed_password = fake_hash_password(form_data.password) if not hashed_password == user.hashed_password: raise HTTPException(status_code=400, detail="Incorrect username or password") return {"access_token": user.username, "token_type": "bearer"} ``` -------------------------------- ### Pydantic Model with JSON Schema Examples Source: https://fastapi.tiangolo.com/tutorial/schema-extra-example Define example data for a Pydantic model using `model_config` and `json_schema_extra`. This data is added to the generated JSON Schema and used in API documentation. ```python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None model_config = { "json_schema_extra": { "examples": [ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, } ] } } @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results ``` -------------------------------- ### Get Enum Value in FastAPI Source: https://fastapi.tiangolo.com/tutorial/path-params Demonstrates how to define an Enum for path parameters and access its value within a path operation. Use `.value` to get the string representation of the enum member. ```Python from enum import Enum from fastapi import FastAPI class ModelName(str, Enum): alexnet = "alexnet" resnet = "resnet" lenet = "lenet" app = FastAPI() @app.get("/models/{model_name}") async def get_model(model_name: ModelName): if model_name is ModelName.alexnet: return {"model_name": model_name, "message": "Deep Learning FTW!"} if model_name.value == "lenet": return {"model_name": model_name, "message": "LeCNN all the images"} return {"model_name": model_name, "message": "Have some residuals"} ``` -------------------------------- ### Create User Model and Get Current User with Annotated Source: https://fastapi.tiangolo.com/tutorial/security/get-current-user Defines a Pydantic User model and a dependency function to get the current user by decoding a token. The current user is then injected into a path operation using Annotated syntax. ```Python from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordBearer from pydantic import BaseModel app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") class User(BaseModel): username: str email: str | None = None full_name: str | None = None disabled: bool | None = None def fake_decode_token(token): return User( username=token + "fakedecoded", email="john@example.com", full_name="John Doe" ) async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): user = fake_decode_token(token) return user @app.get("/users/me") async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]): return current_user ``` -------------------------------- ### Get Own Items Endpoint Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Retrieves items associated with the currently authenticated user. ```APIDOC ## GET /users/me/items/ ### Description Returns a list of items owned by the currently authenticated user. ### Method GET ### Endpoint /users/me/items/ ### Response #### Success Response (200) - Returns a list of item objects, each containing an 'item_id' and the 'owner's username. #### Response Example [ { "item_id": "Foo", "owner": "johndoe" } ] ``` -------------------------------- ### Mount StaticFiles Directory Source: https://fastapi.tiangolo.com/tutorial/static-files Mount a StaticFiles instance to serve files from a 'static' directory under the '/static' path. Requires FastAPI and StaticFiles imports. ```python from fastapi import FastAPI from fastapi.staticfiles import StaticFiles app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") ``` -------------------------------- ### Basic File Reading with Context Manager Source: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield Demonstrates the standard Python way to use a context manager for file operations, ensuring the file is closed after use. ```python with open("./somefile.txt") as f: contents = f.read() print(contents) ``` -------------------------------- ### Configure Documentation UI URLs Source: https://fastapi.tiangolo.com/tutorial/metadata Configure the URLs for Swagger UI and ReDoc using `docs_url` and `redoc_url` parameters. Set to `None` to disable a specific UI. This example sets Swagger UI to '/documentation' and disables ReDoc. ```python from fastapi import FastAPI app = FastAPI(docs_url="/documentation", redoc_url=None) @app.get("/items/") async def read_items(): return [{"name": "Foo"}] ``` -------------------------------- ### Get Current User Endpoint Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Retrieves the currently authenticated user based on the provided JWT. ```APIDOC ## GET /users/me/ ### Description Returns the profile information of the currently authenticated user. ### Method GET ### Endpoint /users/me/ ### Response #### Success Response (200) - **username** (string) - The username of the user. - **email** (string) - The email of the user. - **full_name** (string) - The full name of the user. - **disabled** (boolean) - Indicates if the user account is disabled. #### Response Example { "username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe", "disabled": false } ``` -------------------------------- ### Unpacking Dictionary into UserInDB Model Source: https://fastapi.tiangolo.com/tutorial/security/simple-oauth2 Demonstrates how to unpack a dictionary into a UserInDB model's arguments. This is useful when creating a user instance from a dictionary of user data. ```python UserInDB( username = user_dict["username"], email = user_dict["email"], full_name = user_dict["full_name"], disabled = user_dict["disabled"], hashed_password = user_dict["hashed_password"], ) ``` -------------------------------- ### Import FastAPI App Source: https://fastapi.tiangolo.com/tutorial/bigger-applications This is the equivalent Python import statement for the entrypoint configured in pyproject.toml. ```python from app.main import app ``` -------------------------------- ### Configure FastAPI entrypoint in pyproject.toml Source: https://fastapi.tiangolo.com/tutorial/first-steps Specify the application entrypoint in the pyproject.toml file. This tells the 'fastapi' command where to find your FastAPI app instance. ```toml [tool.fastapi] entrypoint = "main:app" ``` ```toml [tool.fastapi] entrypoint = "backend.main:app" ``` -------------------------------- ### Import File and UploadFile Source: https://fastapi.tiangolo.com/tutorial/request-files Import File and UploadFile from fastapi. Use Annotated for type hinting. This example shows how to create endpoints to receive file content as bytes or as an UploadFile object. ```python from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes, File()]): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename} ``` -------------------------------- ### OAuth2 Scheme Setup Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Configure the OAuth2PasswordBearer scheme to handle token retrieval from the Authorization header. Specify the token URL for authentication. ```python oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") ``` -------------------------------- ### Declare Path Parameter with Annotated and Query Parameter Source: https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations Shows how to declare a path parameter `item_id` and a query parameter `q` using `Annotated` for type hinting and metadata. This approach is generally preferred over the `*` syntax for clarity. ```Python from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get")], q: str ): results = {"item_id": item_id} if q: results.update({"q": q}) return results ``` -------------------------------- ### Get Current User from Token Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Decodes a JWT from the Authorization header, validates it, and retrieves the corresponding user. Raises an HTTPException if validation fails. ```python async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: raise credentials_exception return user ``` -------------------------------- ### Get Current Active User Dependency Source: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt Create a dependency that extends `get_current_user` to check if the user is active. Raises an HTTPException if the user is disabled. ```python async def get_current_active_user( current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user ``` -------------------------------- ### Custom Validator Function Logic Source: https://fastapi.tiangolo.com/tutorial/query-params-str-validations Demonstrates the logic for a custom validator function that checks if a string starts with specific prefixes using `startswith()` with a tuple. ```Python # Code above omitted def check_valid_id(id: str): if not id.startswith(("isbn-", "imdb-")): raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') return id ``` -------------------------------- ### Mix Path, Query, and Body Parameters without Annotated Source: https://fastapi.tiangolo.com/tutorial/body-multiple-params This example shows how to mix path, query, and body parameters without using Annotated, setting the body parameter as optional with a default None value. ```python from fastapi import FastAPI, Path from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int = Path(title="The ID of the item to get", ge=0, le=1000), q: str | None = None, item: Item | None = None, ): results = {"item_id": item_id} if q: results.update({"q": q}) if item: results.update({"item": item}) return results ``` -------------------------------- ### Import FastAPI and Include Routers Source: https://fastapi.tiangolo.com/tutorial/bigger-applications This snippet shows how to import FastAPI, define global dependencies, and include multiple APIRouter instances with specific configurations like prefixes, tags, and responses. ```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!"} ``` -------------------------------- ### Error Response for Extra Form Fields Source: https://fastapi.tiangolo.com/tutorial/request-form-models Example of an error response when a client sends extra, undeclared fields in a form submission to an endpoint configured to forbid them. ```json { "detail": [ { "type": "extra_forbidden", "loc": ["body", "extra"], "msg": "Extra inputs are not permitted", "input": "Mr. Poopybutthole" } ] } ```