← Back to FastAPI map
FastAPI · Foundations

App instance

Create the app object and set the title and version shown in its docs.

core

Overview

Everything starts with app = FastAPI(). That one object is the ASGI application the server runs, the registry that route decorators attach to, and the home of app-wide configuration: docs metadata, middleware, exception handlers, lifespan, and global dependencies.

Key concepts

main:app
How the server finds your application: module main, variable app. Rename either and the run command changes with it.
Metadata
title, version, description and tags appear in the docs and the OpenAPI schema. They describe the API; they do not change how it behaves.
docs_url / redoc_url
Set to None to switch the interactive docs off - common for internal APIs in production.
Return values
Return a dict, list, Pydantic model or dataclass and FastAPI converts it to JSON. Return a Response object to take full control of the output.

Best practices

  • Create the app in one place - main.py or a create_app() factory - so tests can build a fresh instance.
  • Keep version in step with your releases so clients can tell what they are talking to.
  • Hide or protect the docs for internal-only APIs rather than publishing the full schema.

Creating the app

FastAPI() - all constructor params

Core
from fastapi import FastAPI app = FastAPI( title="My API", description="API description shown in docs", version="1.0.0", docs_url="/docs", # set None to disable Swagger redoc_url="/redoc", # set None to disable ReDoc openapi_url="/openapi.json", terms_of_service="https://example.com/terms", contact={"name": "Dev", "email": "dev@rte.dev"}, license_info={"name": "MIT"}, openapi_tags=[ {"name": "users", "description": "User management"}, {"name": "items", "description": "Item CRUD"} ] )

Tip: All params are optional. The bare app = FastAPI() works perfectly for development.

Minimal hello world - annotated

First app
from fastapi import FastAPI app = FastAPI() # create instance @app.get("/") # register GET / route async def root(): return {"message": "Hello!"} # dict -> JSON automatically # FastAPI auto-handles: # ✓ dict/list/Pydantic model -> JSON # ✓ Content-Type: application/json # ✓ /docs, /redoc, /openapi.json # ✓ 422 validation on bad input

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...