* ✨ Pydantic v2 migration, initial implementation (#9500)
* ✨ Add compat layer, for Pydantic v1 and v2
* ✨ Re-export Pydantic needed internals from compat, to later patch them for v1
* ♻️ Refactor internals to use new compatibility layers and run with Pydantic v2
* 📝 Update examples to run with Pydantic v2
* ✅ Update tests to use Pydantic v2
* 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
* ✅ Temporarily disable Peewee tests, afterwards I'll enable them only for Pydantic v1
* 🐛 Fix JSON Schema generation and OpenAPI ref template
* 🐛 Fix model field creation with defaults from Pydantic v2
* 🐛 Fix body field creation, with new FieldInfo
* ✨ Use and check new ResponseValidationError for server validation errors
* ✅ Fix test_schema_extra_examples tests with ResponseValidationError
* ✅ Add dirty-equals to tests for compatibility with Pydantic v1 and v2
* ✨ Add util to regenerate errors with custom loc
* ✨ Generate validation errors with loc
* ✅ Update tests for compatibility with Pydantic v1 and v2
* ✅ Update tests for Pydantic v2 in tests/test_filter_pydantic_sub_model.py
* ✅ Refactor tests in tests/test_dependency_overrides.py for Pydantic v2, separate parameterized into independent tests to use insert_assert
* ✅ Refactor OpenAPI test for tests/test_infer_param_optionality.py for consistency, and make it compatible with Pydantic v1 and v2
* ✅ Update tests for tests/test_multi_query_errors.py for Pydantic v1 and v2
* ✅ Update tests for tests/test_multi_body_errors.py for Pydantic v1 and v2
* ✅ Update tests for tests/test_multi_body_errors.py for Pydantic v1 and v2
* 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
* ♻️ Refactor tests for tests/test_path.py to inline pytest parameters, to make it easier to make them compatible with Pydantic v2
* ✅ Refactor and udpate tests for tests/test_path.py for Pydantic v1 and v2
* ♻️ Refactor and update tests for tests/test_query.py with compatibility for Pydantic v1 and v2
* ✅ Fix test with optional field without default None
* ✅ Update tests for compatibility with Pydantic v2
* ✅ Update tutorial tests for Pydantic v2
* ♻️ Update OAuth2 dependencies for Pydantic v2
* ♻️ Refactor str check when checking for sequence types
* ♻️ Rename regex to pattern to keep in sync with Pydantic v2
* ♻️ Refactor _compat.py, start moving conditional imports and declarations to specifics of Pydantic v1 or v2
* ✅ Update tests for OAuth2 security optional
* ✅ Refactor tests for OAuth2 optional for Pydantic v2
* ✅ Refactor tests for OAuth2 security for compatibility with Pydantic v2
* 🐛 Fix location in compat layer for Pydantic v2 ModelField
* ✅ Refactor tests for Pydantic v2 in tests/test_tutorial/test_bigger_applications/test_main_an_py39.py
* 🐛 Add missing markers in Python 3.9 tests
* ✅ Refactor tests for bigger apps for consistency with annotated ones and with support for Pydantic v2
* 🐛 Fix jsonable_encoder with new Pydantic v2 data types and Url
* 🐛 Fix invalid JSON error for compatibility with Pydantic v2
* ✅ Update tests for behind_a_proxy for Pydantic v2
* ✅ Update tests for tests/test_tutorial/test_body/test_tutorial001_py310.py for Pydantic v2
* ✅ Update tests for tests/test_tutorial/test_body/test_tutorial001.py with Pydantic v2 and consistency with Python 3.10 tests
* ✅ Fix tests for tutorial/body_fields for Pydantic v2
* ✅ Refactor tests for tutorial/body_multiple_params with Pydantic v2
* ✅ Update tests for tutorial/body_nested_models for Pydantic v2
* ✅ Update tests for tutorial/body_updates for Pydantic v2
* ✅ Update test for tutorial/cookie_params for Pydantic v2
* ✅ Fix tests for tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py for Pydantic v2
* ✅ Update tests for tutorial/dataclasses for Pydantic v2
* ✅ Update tests for tutorial/dependencies for Pydantic v2
* ✅ Update tests for tutorial/extra_data_types for Pydantic v2
* ✅ Update tests for tutorial/handling_errors for Pydantic v2
* ✅ Fix test markers for Python 3.9
* ✅ Update tests for tutorial/header_params for Pydantic v2
* ✅ Update tests for Pydantic v2 in tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
* ✅ Fix extra tests for Pydantic v2
* ✅ Refactor test for parameters, to later fix Pydantic v2
* ✅ Update tests for tutorial/query_params for Pydantic v2
* ♻️ Update examples in docs to use new pattern instead of the old regex
* ✅ Fix several tests for Pydantic v2
* ✅ Update and fix test for ResponseValidationError
* 🐛 Fix check for sequences vs scalars, include bytes as scalar
* 🐛 Fix check for complex data types, include UploadFile
* 🐛 Add list to sequence annotation types
* 🐛 Fix checks for uploads and add utils to find if an annotation is an upload (or bytes)
* ✨ Add UnionType and NoneType to compat layer
* ✅ Update tests for request_files for compatibility with Pydantic v2 and consistency with other tests
* ✅ Fix testsw for request_forms for Pydantic v2
* ✅ Fix tests for request_forms_and_files for Pydantic v2
* ✅ Fix tests in tutorial/security for compatibility with Pydantic v2
* ⬆️ Upgrade required version of email_validator
* ✅ Fix tests for params repr
* ✅ Add Pydantic v2 pytest markers
* Use match_pydantic_error_url
* 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
* Use field_serializer instead of encoders in some tests
* Show Undefined as ... in repr
* Mark custom encoders test with xfail
* Update test to reflect new serialization of Decimal as str
* Use `model_validate` instead of `from_orm`
* Update JSON schema to reflect required nullable
* Add dirty-equals to pyproject.toml
* Fix locs and error creation for use with pydantic 2.0a4
* Use the type adapter for serialization. This is hacky.
* 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
* ✅ Refactor test_multi_body_errors for compatibility with Pydantic v1 and v2
* ✅ Refactor test_custom_encoder for Pydantic v1 and v2
* ✅ Set input to None for now, for compatibility with current tests
* 🐛 Fix passing serialization params to model field when handling the response
* ♻️ Refactor exceptions to not depend on Pydantic ValidationError class
* ♻️ Revert/refactor params to simplify repr
* ✅ Tweak tests for custom class encoders for Pydantic v1 and v2
* ✅ Tweak tests for jsonable_encoder for Pydantic v1 and v2
* ✅ Tweak test for compatibility with Pydantic v1 and v2
* 🐛 Fix filtering data with subclasses
* 🐛 Workaround examples in OpenAPI schema
* ✅ Add skip marker for SQL tutorial, needs to be updated either way
* ✅ Update test for broken JSON
* ✅ Fix test for broken JSON
* ✅ Update tests for timedeltas
* ✅ Fix test for plain text validation errors
* ✅ Add markers for Pydantic v1 exclusive tests (for now)
* ✅ Update test for path_params with enums for compatibility with Pydantic v1 and v2
* ✅ Update tests for extra examples in OpenAPI
* ✅ Fix tests for response_model with compatibility with Pydantic v1 and v2
* 🐛 Fix required double serialization for different types of models
* ✅ Fix tests for response model with compatibility with new Pydantic v2
* 🐛 Import Undefined from compat layer
* ✅ Fix tests for response_model for Pydantic v2
* ✅ Fix tests for schema_extra for Pydantic v2
* ✅ Add markers and update tests for Pydantic v2
* 💡 Comment out logic for double encoding that breaks other usecases
* ✅ Update errors for int parsing
* ♻️ Refactor re-enabling compatibility for Pydantic v1
* ♻️ Refactor OpenAPI utils to re-enable support for Pydantic v1
* ♻️ Refactor dependencies/utils and _compat for compatibility with Pydantic v1
* 🐛 Fix and tweak compatibility with Pydantic v1 and v2 in dependencies/utils
* ✅ Tweak tests and examples for Pydantic v1
* ♻️ Tweak call to ModelField.validate for compatibility with Pydantic v1
* ✨ Use new global override TypeAdapter from_attributes
* ✅ Update tests after updating from_attributes
* 🔧 Update pytest config to avoid collecting tests from docs, useful for editor-integrated tests
* ✅ Add test for data filtering, including inheritance and models in fields or lists of models
* ♻️ Make OpenAPI models compatible with both Pydantic v1 and v2
* ♻️ Fix compatibility for Pydantic v1 and v2 in jsonable_encoder
* ♻️ Fix compatibility in params with Pydantic v1 and v2
* ♻️ Fix compatibility when creating a FieldInfo in Pydantic v1 and v2 in utils.py
* ♻️ Fix generation of flat_models and JSON Schema definitions in _compat.py for Pydantic v1 and v2
* ♻️ Update handling of ErrorWrappers for Pydantic v1
* ♻️ Refactor checks and handling of types an sequences
* ♻️ Refactor and cleanup comments with compatibility for Pydantic v1 and v2
* ♻️ Update UploadFile for compatibility with both Pydantic v1 and v2
* 🔥 Remove commented out unneeded code
* 🐛 Fix mock of get_annotation_from_field_info for Pydantic v1 and v2
* 🐛 Fix params with compatibility for Pydantic v1 and v2, with schemas and new pattern vs regex
* 🐛 Fix check if field is sequence for Pydantic v1
* ✅ Fix tests for custom_schema_fields, for compatibility with Pydantic v1 and v2
* ✅ Simplify and fix tests for jsonable_encoder with compatibility for Pydantic v1 and v2
* ✅ Fix tests for orm_mode with Pydantic v1 and compatibility with Pydantic v2
* ♻️ Refactor logic for normalizing Pydantic v1 ErrorWrappers
* ♻️ Workaround for params with examples, before defining what to deprecate in Pydantic v1 and v2 for examples with JSON Schema vs OpenAPI
* ✅ Fix tests for Pydantic v1 and v2 for response_by_alias
* ✅ Fix test for schema_extra with compatibility with Pydantic v1 and v2
* ♻️ Tweak error regeneration with loc
* ♻️ Update error handling and serializationwith compatibility for Pydantic v1 and v2
* ♻️ Re-enable custom encoders for Pydantic v1
* ♻️ Update ErrorWrapper reserialization in Pydantic v1, do it outside of FastAPI ValidationExceptions
* ✅ Update test for filter_submodel, re-structure to simplify testing while keeping division of Pydantic v1 and v2
* ✅ Refactor Pydantic v1 only test that requires modifying environment variables
* 🔥 Update test for plaintext error responses, for Pydantic v1 and v2
* ⏪️ Revert changes in DB tutorial to use Pydantic v1 (the new guide will have SQLModel)
* ✅ Mark current SQL DB tutorial tests as Pydantic only
* ♻️ Update datastructures for compatibility with Pydantic v1, not requiring pydantic-core
* ♻️ Update encoders.py for compatibility with Pydantic v1
* ⏪️ Revert changes to Peewee, the docs for that are gonna live in a new HowTo section, not in the main tutorials
* ♻️ Simplify response body kwargs generation
* 🔥 Clean up comments
* 🔥 Clean some tests and comments
* ✅ Refactor tests to match new Pydantic error string URLs
* ✅ Refactor tests for recursive models for Pydantic v1 and v2
* ✅ Update tests for Peewee, re-enable, Pydantic-v1-only
* ♻️ Update FastAPI params to take regex and pattern arguments
* ⏪️ Revert tutorial examples for pattern, it will be done in a subsequent PR
* ⏪️ Revert changes in schema extra examples, it will be added later in a docs-specific PR
* 💡 Add TODO comment to document str validations with pattern
* 🔥 Remove unneeded comment
* 📌 Upgrade Pydantic pin dependency
* ⬆️ Upgrade email_validator dependency
* 🐛 Tweak type annotations in _compat.py
* 🔇 Tweak mypy errors for compat, for Pydantic v1 re-imports
* 🐛 Tweak and fix type annotations
* ➕ Update requirements-test.txt, re-add dirty-equals
* 🔥 Remove unnecessary config
* 🐛 Tweak type annotations
* 🔥 Remove unnecessary type in dependencies/utils.py
* 💡 Update comment in routing.py
---------
Co-authored-by: David Montague <35119617+dmontagu@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* 👷 Add CI for both Pydantic v1 and v2 (#9688)
* 👷 Test and install Pydantic v1 and v2 in CI
* 💚 Tweak CI config for Pydantic v1 and v2
* 💚 Fix Pydantic v2 specification in CI
* 🐛 Fix type annotations for compatibility with Python 3.7
* 💚 Install Pydantic v2 for lints
* 🐛 Fix type annotations for Pydantic v2
* 💚 Re-use test cache for lint
* ♻️ Refactor internals for test coverage and performance (#9691)
* ♻️ Tweak import of Annotated from typing_extensions, they are installed anyway
* ♻️ Refactor _compat to define functions for Pydantic v1 or v2 once instead of checking inside
* ✅ Add test for UploadFile for Pydantic v2
* ♻️ Refactor types and remove logic for impossible cases
* ✅ Add missing tests from test refactor for path params
* ✅ Add tests for new decimal encoder
* 💡 Add TODO comment for decimals in encoders
* 🔥 Remove unneeded dummy function
* 🔥 Remove section of code in field_annotation_is_scalar covered by sub-call to field_annotation_is_complex
* ♻️ Refactor and tweak variables and types in _compat
* ✅ Add tests for corner cases and compat with Pydantic v1 and v2
* ♻️ Refactor type annotations
* 🔖 Release version 0.100.0-beta1
* ♻️ Refactor parts that use optional requirements to make them compatible with installations without them (#9707)
* ♻️ Refactor parts that use optional requirements to make them compatible with installations without them
* ♻️ Update JSON Schema for email field without email-validator installed
* 🐛 Fix support for Pydantic v2.0, small changes in their final release (#9771)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* 🔖 Release version 0.100.0-beta2
* ✨ OpenAPI 3.1.0 with Pydantic v2, merge `master` (#9773)
* ➕ Add dirty-equals as a testing dependency (#9778)
➕ Add dirty-equals as a testing dependency, it seems it got lsot at some point
* 🔀 Merge master, fix valid JSON Schema accepting bools (#9782)
* ⏪️ Revert usage of custom logic for TypeAdapter JSON Schema, solved on the Pydantic side (#9787)
⏪️ Revert usage of custom logic for TypeAdapter JSON Schema, solved on Pydantic side
* ♻️ Deprecate parameter `regex`, use `pattern` instead (#9786)
* 📝 Update docs to deprecate regex, recommend pattern
* ♻️ Update examples to use new pattern instead of regex
* 📝 Add new example with deprecated regex
* ♻️ Add deprecation notes and warnings for regex
* ✅ Add tests for regex deprecation
* ✅ Update tests for compatibility with Pydantic v1
* ✨ Update docs to use Pydantic v2 settings and add note and example about v1 (#9788)
* ➕ Add pydantic-settings to all extras
* 📝 Update docs for Pydantic settings
* 📝 Update Settings source examples to use Pydantic v2, and add a Pydantic v1 version
* ✅ Add tests for settings with Pydantic v1 and v2
* 🔥 Remove solved TODO comment
* ♻️ Update conditional OpenAPI to use new Pydantic v2 settings
* ✅ Update tests to import Annotated from typing_extensions for Python < 3.9 (#9795)
* ➕ Add pydantic-extra-types to fastapi[extra]
* ➕ temp: Install Pydantic from source to test JSON Schema metadata fixes (#9777)
* ➕ Install Pydantic from source, from branch for JSON Schema with metadata
* ➕ Update dependencies, install Pydantic main
* ➕ Fix dependency URL for Pydantic from source
* ➕ Add pydantic-settings for test requirements
* 💡 Add TODO comments to re-enable Pydantic main (not from source) (#9796)
* ✨ Add new Pydantic Field param options to Query, Cookie, Body, etc. (#9797)
* 📝 Add docs for Pydantic v2 for `docs/en/docs/advanced/path-operation-advanced-configuration.md` (#9798)
* 📝 Update docs in examples for settings with Pydantic v2 (#9799)
* 📝 Update JSON Schema `examples` docs with Pydantic v2 (#9800)
* ♻️ Use new Pydantic v2 JSON Schema generator (#9813)
Co-authored-by: David Montague <35119617+dmontagu@users.noreply.github.com>
* ♻️ Tweak type annotations and Pydantic version range (#9801)
* 📌 Re-enable GA Pydantic, for v2, require minimum 2.0.2 (#9814)
* 🔖 Release version 0.100.0-beta3
* 🔥 Remove duplicate type declaration from merge conflicts (#9832)
* 👷♂️ Run tests with Pydantic v2 GA (#9830)
👷 Run tests for Pydantic v2 GA
* 📝 Add notes to docs expecting Pydantic v2 and future updates (#9833)
* 📝 Update index with new extras
* 📝 Update release notes
---------
Co-authored-by: David Montague <35119617+dmontagu@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Pastukhov Nikita <diementros@yandex.ru>
* 🐛 Fix JSON Schema accepting bools as valid JSON Schemas, e.g. additionalProperties: false
* ✅ Add test to ensure additionalProperties can be false
* ♻️ Tweak OpenAPI models to support Pydantic v1's JSON Schema for tuples
* 📝 Update source examples to use new JSON Schema examples field
* ✅ Update tests for JSON Schema examples
* 📝 Update highlights in JSON Schema examples
* ✨ Update OpenAPI models for JSON Schema 2020-12 and OpenAPI 3.1.0
* ✨ Add support for summary and webhooks
* ✨ Update JSON Schema for UploadFiles
* ⏪️ Revert making paths optional, to ensure always correctness
* ⏪️ Keep UploadFile as format: binary for compatibility with the rest of Pydantic bytes fields in v1
* ✨ Update version of OpenAPI generated to 3.1.0
* ✨ Update the version of Swagger UI
* 📝 Update docs about extending OpenAPI
* 📝 Update docs and links to refer to OpenAPI 3.1.0
* ✨ Update logic for handling webhooks
* ♻️ Update parameter functions and classes, deprecate example and make examples the main field
* ✅ Update tests for OpenAPI 3.1.0
* 📝 Update examples for OpenAPI metadata
* ✅ Add and update tests for OpenAPI metadata
* 📝 Add source example for webhooks
* 📝 Update docs for metadata
* 📝 Update docs for Schema extra
* 📝 Add docs for webhooks
* 🔧 Add webhooks docs to MkDocs
* ✅ Update tests for extending OpenAPI
* ✅ Add tests for webhooks
* ♻️ Refactor generation of OpenAPI and JSON Schema with params
* 📝 Update source examples for field examples
* ✅ Update tests for examples
* ➕ Make sure the minimum version of typing-extensions installed has deprecated() (already a dependency of Pydantic)
* ✏️ Fix typo in Webhooks example code
* 🔥 Remove commented out code of removed nullable field
* 🗑️ Add deprecation warnings for example argument
* ✅ Update tests to check for deprecation warnings
* ✅ Add test for webhooks with security schemes, for coverage
* 🍱 Update image for metadata, with new summary
* 🍱 Add docs image for Webhooks
* 📝 Update docs for webhooks, add docs UI image
* ➕ Add dependencies for MkDocs Insiders
* 🙈 Add Insider's .cache to .gitignore
* 🔧 Update MkDocs configs for Insiders
* 💄 Add custom Insiders card layout, while the custom logo is provided from upstream
* 🔨 Update docs.py script to dynamically enable insiders if it's installed
* 👷 Add cache for MkDocs Material Insiders' cards
* 🔊 Add a small log to the docs CLI
* 🔊 Tweak logs, only after exporting languages
* 🐛 Fix accessing non existing env var
* 🔧 Invalidate deps cache
* 🔧 Tweak cache IDs
* 👷 Update cache for installing insiders
* 🔊 Log insiders
* 💚 Invalidate cache
* 👷 Tweak cache keys
* 👷 Trigger CI and test cache
* 🔥 Remove cache comment
* ⚡️ Optimize cache usage for first runs of docs
* 👷 Tweak cache for MkDocs Material cards
* 💚 Trigger CI to test cache
* ✨ Add MkDocs hooks to re-use all config from en, and auto-generate missing docs files form en
* 🔧 Update MkDocs config for es
* 🔧 Simplify configs for all languages
* ✨ Compute available languages from MkDocs Material for config overrides in hooks
* 🔧 Update config for MkDocs for en, to make paths compatible for other languages
* ♻️ Refactor scripts/docs.py to remove all custom logic that is now handled by the MkDocs hooks
* 🔧 Remove ta language as it's incomplete (no translations and causing errors)
* 🔥 Remove ta lang, no translations available
* 🔥 Remove dummy overrides directories, no longer needed
* ✨ Use the same missing-translation.md file contents for hooks
* ⏪️ Restore and refactor new-lang command
* 📝 Update docs for contributing with new simplified workflow for translations
* 🔊 Enable logs so that MkDocs can show its standard output on the docs.py script
Update for docs/tutorial/schema-extra-example.md
When working on the translation, I noticed that this page is missing the annotated tips that can be found in the rest of the documentation (I checked, and it's the only page where they're missing).
Set minimal hatchling version needed to build the package
Set the minimal hatchling version that is needed to build fastapi to
1.13.0. Older versions fail to build because they do not recognize
the trove classifiers used, e.g. 1.12.2 yields:
ValueError: Unknown classifier in field `project.classifiers`: Framework :: Pydantic
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Fix: copy FieldInfo from Annotated arguments
We need to copy the field_info to prevent ourselves from
mutating it. This allows multiple path or nested routers ,etc.
* 📝 Add comment in fastapi/dependencies/utils.py
Co-authored-by: Nadav Zingerman <7372858+nzig@users.noreply.github.com>
* ✅ Extend and tweak tests for Annotated
* ✅ Tweak coverage, it's probably covered by a different version of Python
---------
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Co-authored-by: Nadav Zingerman <7372858+nzig@users.noreply.github.com>
* 🌐💬🩺 🦲
* 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
* 🛠️😊
* ♻️ Rename emoji lang from emj to em, and main docs name as 😉
---------
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Axd1x8a <26704473+FeeeeK@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* 🍱 Add new source examples with Annotated for Query Params and String Validations
* 📝 Add new docs with Annotated for Query Params and String Validations
* 🚚 Rename incorrectly named tests for Query Params and str validations
* ✅ Add new tests with Annotated for Query Params and Sring Validations examples
* 🍱 Add new examples with Annotated for Intro to Python Types
* 📝 Update Python Types Intro, include Annotated
* 🎨 Fix formatting in Query params and string validation, and highlight
* 🍱 Add new Annotated source examples for Path Params and Numeric Validations
* 📝 Update docs for Path Params and Numeric Validations with Annotated
* 🍱 Add new source examples with Annotated for Body - Multiple Params
* 📝 Update docs with Annotated for Body - Multiple Parameters
* ✅ Add test for new Annotated examples in Body - Multiple Parameters
* 🍱 Add new Annotated source examples for Body Fields
* 📝 Update docs for Body Fields with new Annotated examples
* ✅ Add new tests for new Annotated examples for Body Fields
* 🍱 Add new Annotated source examples for Schema Extra (Example Data)
* 📝 Update docs for Schema Extra with Annotated
* ✅ Add tests for new Annotated examples for Schema Extra
* 🍱 Add new Annnotated source examples for Extra Data Types
* 📝 Update docs with Annotated for Extra Data Types
* ✅ Add tests for new Annotated examples for Extra Data Types
* 🍱 Add new Annotated source examples for Cookie Parameters
* 📝 Update docs for Cookie Parameters with Annotated examples
* ✅ Add tests for new Annotated source examples in Cookie Parameters
* 🍱 Add new Annotated examples for Header Params
* 📝 Update docs with Annotated examples for Header Parameters
* ✅ Add tests for new Annotated examples for Header Params
* 🍱 Add new Annotated examples for Form Data
* 📝 Update Annotated docs for Form Data
* ✅ Add tests for new Annotated examples in Form Data
* 🍱 Add new Annotated source examples for Request Files
* 📝 Update Annotated docs for Request Files
* ✅ Test new Annotated examples for Request Files
* 🍱 Add new Annotated source examples for Request Forms and Files
* ✅ Add tests for new Anotated examples for Request Forms and Files
* 🍱 Add new Annotated source examples for Dependencies and Advanced Dependencies
* ✅ Add tests for new Annotated dependencies
* 📝 Add new docs for using Annotated with dependencies including type aliases
* 📝 Update docs for Classes as Dependencies with Annotated
* 📝 Update docs for Sub-dependencies with Annotated
* 📝 Update docs for Dependencies in path operation decorators with Annotated
* 📝 Update docs for Global Dependencies with Annotated
* 📝 Update docs for Dependencies with yield with Annotated
* 🎨 Update format in example for dependencies with Annotated
* 🍱 Add source examples with Annotated for Security
* ✅ Add tests for new Annotated examples for security
* 📝 Update docs for Security - First Steps with Annotated
* 📝 Update docs for Security: Get Current User with Annotated
* 📝 Update docs for Simple OAuth2 with Password and Bearer with Annotated
* 📝 Update docs for OAuth2 with Password (and hashing), Bearer with JWT tokens with Annotated
* 📝 Update docs for Request Forms and Files with Annotated
* 🍱 Add new source examples for Bigger Applications with Annotated
* ✅ Add new tests for Bigger Applications with Annotated
* 📝 Update docs for Bigger Applications - Multiple Files with Annotated
* 🍱 Add source examples for background tasks with Annotated
* 📝 Update docs for Background Tasks with Annotated
* ✅ Add test for Background Tasks with Anotated
* 🍱 Add new source examples for docs for Testing with Annotated
* 📝 Update docs for Testing with Annotated
* ✅ Add tests for Annotated examples for Testing
* 🍱 Add new source examples for Additional Status Codes with Annotated
* ✅ Add tests for new Annotated examples for Additional Status Codes
* 📝 Update docs for Additional Status Codes with Annotated
* 📝 Update docs for Advanced Dependencies with Annotated
* 📝 Update docs for OAuth2 scopes with Annotated
* 📝 Update docs for HTTP Basic Auth with Annotated
* 🍱 Add source examples with Annotated for WebSockets
* ✅ Add tests for new Annotated examples for WebSockets
* 📝 Update docs for WebSockets with new Annotated examples
* 🍱 Add source examples with Annotated for Settings and Environment Variables
* 📝 Update docs for Settings and Environment Variables with Annotated
* 🍱 Add new source examples for testing dependencies with Annotated
* ✅ Add tests for new examples for testing dependencies
* 📝 Update docs for testing dependencies with new Annotated examples
* ✅ Update and fix marker for Python 3.9 test
* 🔧 Update Ruff ignores for source examples in docs
* ✅ Fix some tests in the grid for Python 3.9 (incorrectly testing 3.10)
* 🔥 Remove source examples and tests for (non existent) docs section about Annotated, as it's covered in all the rest of the docs
* 📝 Add docs recommending Union over Optional
* 📝 Update docs recommending Union over Optional
* 📝 Update source examples for docs, recommend Union over Optional
* 📝 Update highlighted lines with updated source examples
* 📝 Update highlighted lines in Markdown with recent code changes
* 📝 Update docs, use Union instead of Optional
* ♻️ Update source examples to recommend Union over Optional
* 🎨 Update highlighted code in Markdown after moving from Optional to Union
* ✨ Do not require default value in Query(), Path(), Header(), etc
* 📝 Update source examples for docs with default and required values
* ✅ Update tests with new default values and not required Ellipsis
* 📝 Update docs for Query params and update info about default value, required, Ellipsis
* 🔧 Add first pre-commit config
* 🎨 Format YAML files with pre-commit
* 🎨 Format Markdown with pre-commit
* 🎨 Format SVGs, drawio, JS, HTML with pre-commit
* ➕ Add pre-commit to dev dependencies
* ⬇️ Extend pre-commit range to support Python 3.6
A beginner article in German to get started with the FastAPI with a small Todo API as an example.
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* ⬆️ Upgrade Uvicorn when installing fastapi[all] to the latest version, including uvloop
* ⬆️ Relax Uvicorn version range to the minimum supported
in case anyone depends older versions somehow installed with FastAPI extras
* ✨ Add language selector widget
* 🔧 Update script to re-generate MkDocs configs, including langs widget
* 🔧 Update languages MkDocs configs, with lang selector widget
* 🙈 Add .gitignore files to keep overrides directories for translations to fix serving live locally during translations
* ♻️ Refactor docs scripts to handle language overrides (newsletter notification)
* ✨ Add Default and DefaultPlaceholder data structures
to handle defaults and overrides
* ✨ Add utils to get values by priority handling DefaultPlaceholders
* ✨ Add support for top-level parameters in FastAPI, APIRouter, include_router
including: prefix, tags, dependencies, deprecated, include_in_schema, responses, default_response_class, callbacks
* ♻️ Update openapi utils to handle DefaultPlaceholder for response_class
* 📝 Update bigger-application example code to use top-level params
and showcase them in APIRouter, FastAPI, include_router
* 📝 Update docs for Bigger Applications, include diagrams, top-level params
* 🔥 Simplify code and docs for callbacks as default_response_class is no longer required
* 📝 Add docs for top-level dependencies, in FastAPI()
* 📝 Add docs reference to top-level dependencies in docs for decorator
* ✅ Update/increase tests for Bigger Applications including shared parameters
* ✅ Add tests for top-level dependencies in FastAPI()
* ✅ Add tests for internal DefaultPlaceholder
* ✅ Update/increase tests for callbacks with top-level parameters
* ✅ Add LOTS of tests covering branches and cases for shared parameters
in top-level FastAPI, path operations, include_router, APIRouter, its path operations, nested include_router, nested APIRouter, and its path operations
* 🎨 Format/reorder parameters for consistency in FastAPI, APIRouter, include_router
* ⬆️ Upgrade Material for MkDocs
* ⬆️ Install Material for MkDocs Insiders on CI
* 🔧 Update MkDocs configs to use Material for MkDocs Insiders
* ✨ Use the lightbulb because it looks nice 💡
* 💚 Fix GitHub Action workflow syntax for building docs
* 🐛 Fix GitHub Actions workflow syntax, strike one ⚾
* docs: fix typo in chapter "Request Body" in "Tutorial - User Guide"
* docs: modify a sentence in chapter "Query Parameters and String Validations" in "Tutorial - User Guide"
* docs: fix two grammatical mistakes in chapter "Path Parameters and Numeric Validations" in "Tutorial - User Guide"
* 🔥 Disable action Watch Docs Previews
* 🔧 Use predefined name for docs artifacts for previews
* ✨ Add new GitHub Action Comment Docs Preview in PR
* 🔧 Refactor GitHub Action Preview Docs to work as workflow_run using new action to extract where to comment
* 👥 Update FastAPI People
* ✨ Add first version of FastAPI People GitHub action code
* 🐳 Add Docker and configs for the FastAPI People GitHub Action
* 👷 Add GitHub Action workflow for FastAPI People
* 📝 Add FastAPI People to docs
* 💄 Add custom CSSs for FastAPI People
* 🔥 Remove support for Pydantic < 1.0
* 🔥 Remove deprecated skip_defaults from jsonable_encoder and set default for exclude to None, as in Pydantic
* ♻️ Set default of response_model_exclude=None as in Pydantic
* ⬆️ Require Pydantic >=1.0.0 in requirements
* Check if Form exists and multipart is in virtual environment
* Remove unused import
* Move BodyFieldInfo check to separate helper function
* Fix type UploadFile to File for BodyFieldInfo check
* Working solution. Kind of nasty though.
* Use better method of determing if correct package imported
* Use better method of determing if correct package imported
* Add raising exceptions, update error messages
* Check if Form exists and multipart is in virtual environment
* Move BodyFieldInfo check to separate helper function
* Fix type UploadFile to File for BodyFieldInfo check
* Use better method of determing if correct package imported
* Add raising exceptions, update error messages
* Removed unused import, added comments
Co-authored-by: Christopher Nguyen <chrisngyn99@gmail.com>
* Updated what kind of exception will be thrown
* Add type annotations
Adds annotations to is_form_data
* Fix import order
* Add basic tests
* Fixed Travis tests
* Replace logging with fastapi logger
* Change AttributeError to ImportError to fix exception handling
* Fixing tests
* Catch ModuleNotFoundError first
Fix code coverage
* Update fastapi/dependencies/utils.py
Remove error spaces when printing
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
* Update fastapi/dependencies/utils.py
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
* Removed spaces in error printing
* ♻️ Refactor form data detection
* ✅ Update/increase tests for incorrect multipart install
* 🔥 Remove deprecated Travis (moved to GitHub Actions)
Co-authored-by: yk396 <yk396@cornell.edu>
Co-authored-by: Christopher Nguyen <chrisngyn99@gmail.com>
Co-authored-by: Kai Chen <kaichen120@gmail.com>
Co-authored-by: Chris N <hello@chris-nguyen.me>
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
* Add link in sql-databases.md tutorial section to async-sql-databases.md in advanced section.
* 🎨 Update note format
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* 🔥 Remove deploy badge that won't show correctly until next release
after the fixes to the Gitter bot
* 🐛 Fix GitHub Action to upload docs artifacts with commit from PR, not pre-merge
* ♻️ Run zip docs and artifact upload only on PRs
* 🐛 Fix Gitter notification, use development gitter room until next release
* 🔥 Remove trigger docs preview step from build-docs workflow
as it requires a more privileged token, so it's now triggered by the preview docs watcher
* 🔊 Dump context when building to allow debugging how to refactor the Gitter bot
* add test for get request body's openapi schema
* 📝 Update docs note for GET requests with body
* ✅ Update test for GET request with body, test it receives the body
* 🔇 Temporary type ignore while it's handled in Pydantic
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* 📝 Update JWT docs with python-jose
* 📝 Update format and use python-jose in docs
* ➕ Add Python-jose to dependencies
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* root_path included in servers object instead of path prefix
* ♻️ Refactor implementation of auto-including root_path in OpenAPI servers
* 📝 Update docs and examples for Behind a Proxy, including servers
* 📝 Update Extending OpenAPI as openapi_prefix is no longer needed
* ✅ Add extra tests for root_path in servers and root_path_in_servers=False
* 🍱 Update security docs images with relative token URL
* 📝 Update security docs with relative token URL
* 📝 Update example sources with relative token URLs
* ✅ Update tests with relative tokens
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* ➕ Add mkdocs-markdownextradata-plugin for docs
* 🔧 Update MkDocs config file(s) to include external data
* ✨ Add external links data file
* 📝 Use external data file in External Links
* ♻️ Update data files for langs
The cost is some duplication 😔, these files are updated by the script, but to be able to serve locally they have to be duplicated
* ✨ Update docs script to copy data files
* 🔥 Remove needed duplication of data files for live docs in translations
* ♻️ Remove required extra steps to test in editor
* 🎨 Format lint script
* 📝 Remove obsolete extra steps required to test in editor from docs
* 🐛 Fix coverage
* Update isort script to match changes in the new release, isort v5.0.2
* Downgrade isort to version v4.3.21
* Add an alternative flag to --recursive in isort v5.0.2
* Add isort config file
* 🚚 Import from docs_src for tests
* 🎨 Format dependencies.utils
* 🎨 Remove isort combine_as_imports, keep black profile
* 🔧 Update isort config, use pyproject.toml, Black profile
* 🔧 Update format scripts to use explicit directories to format
otherwise it would try to format venv env directories, I have several with different Python versions
* 🎨 Format NoSQL tutorial after re-sorting imports
* 🎨 Fix format for __init__.py
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Updated .py files with Optional tag (up to body_nested_models)
* Update optionals
* docs_src/ all updates, few I was unsure of
* Updated markdown files with Optional param
* es: Add Optional typing to index.md
* Last of markdown files updated with Optional param
* Update highlight lines
* it: Add Optional typings
* README.md: Update with Optional typings
* Update more highlight increments
* Update highlights
* schema-extra-example.md: Update highlights
* updating highlighting on website to reflect .py changes
* Update highlighting for query-params & response-directly
* Address PR comments
* Get rid of unnecessary comment
* ⏪ Revert Optional in Chinese docs as it probably also requires changes in text
* 🎨 Apply format
* ⏪ Revert modified example
* ♻️ Simplify example in docs
* 📝 Update OpenAPI callback example to use Optional
* ✨ Add Optional types to tests
* 📝 Update docs about query params, default to using Optional
* 🎨 Update code examples line highlighting
* 📝 Update nested models docs to use "type parameters" instead of "subtypes"
* 📝 Add notes about FastAPI usage of None
including:
= None
and
= Query(None)
and clarify relationship with Optional[str]
* 📝 Add note about response_model_by_alias
* ♻️ Simplify query param list example
* 🔥 Remove test for removed example
* ✅ Update test for updated example
Co-authored-by: Christopher Nguyen <chrisngyn99@gmail.com>
Co-authored-by: yk396 <yk396@cornell.edu>
Co-authored-by: Kai Chen <kaichen120@gmail.com>
* Make openapi models honor response_model_by_alias
* Add test for response_model_by_alias working with openapi models
* ⏪ Revert changes
* ✅ Update and extend tests for response_model_by_alias
* ⏪ Revert test name change
* 📌 Pin Pytest and Pytest-Cov
Co-authored-by: Martin Zaťko <martin.zatko@kiwi.com>
* feat: add servers option for OpenAPI
Closes#872
* ✨ Use dicts for OpenAPI servers
* ♻️ Update OpenAPI Server model to support relative URLs
* ✅ Add tests for OpenAPI servers
* ♻️ Re-order parameter location of servers for OpenAPI
* 🎨 Format code
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* fix websockets/tutorial002.py
* fix tutorial002 in ws to correspond with test case
* reformat websocket tutorial002
* fix websocket tutorial002 coverage
* 📝 Update example for WebSockets with Depends
* ✅ Update and refactor tests for WebSockets with dependencies
* 👷 Trigger Travis, as it's not reporting to Codecov
* ✅ Update WebSocket tests to raise coverage
Co-authored-by: Chih Sean Hsu <Sean@Sean-Mac.local>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Normalise IntEnums to ints for route status codes
Closes#1349
* add tests for status code enum support
* add docs for status code enum support
* add endpoint test for enum status code
* 📝 Update note about http.HTTPStatus
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* ➕ Add docs to default_response_class
* ✅ create a tip
* ✅ fixing the tip
* 🚑 grammar
* 📝 Update docs for default response class
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Documented additional parameters
These are included in a recent PR (https://github.com/tiangolo/fastapi/pull/1166) but not in the docs yet.
* response_model_exclude_none
* response_model_exclude_defaults
* 📝 Update note about response_model_exclude_defaults and response_model_exclude_none
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Added test for repeating cookies in response headers
* update `response` headers, status code to match `sub_response` in `solve_dependencies` only if necessary; fix formatting of scottsmith2gmail's test
* restore code coverage, remove dead code from `solve_dependencies`
Co-authored-by: Scott Smith <scott.smith.2@gmail.com>
* Request body error, raise RequestValidationError instead of HTTPException in case JSON decode failure
* add missing test case for body general exception
* Allow to add OpenAPI tag descriptions
* fix type hint
* fix type hint 2
* refactor test to assure 100% coverage
* 📝 Update tags metadata example
* 📝 Update docs for tags metadata
* ✅ Move tags metadata test to tutorial subdir
* 🎨 Update format in applications
* 🍱 Update docs UI image based on new example
* 🎨 Apply formatting after solving conflicts
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* repr description added to Depends class
* repr description added to Security subclass
* get rid of __repr__ in security since it will inherit from super
* make code format consistent with rest
* add desc for rest of the classes
* Update fastapi/params.py
remove trailing whitespace
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
* Implement __repr__
* fix formatting
* formatting again
* ran formatting
* added basic testing
* basic tests added to rest of the classes
* added more test coverage and simplified test file
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
Co-authored-by: Jayati Shrivastava <gaurijove@gmail.com>
* docs: Fix pydantic example in python-types.md
* 📝 Update Python Types Intro to include Optional
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Fix callable class generator dependencies
* workaround to support asynccontextmanager backfill for pre python3.7
Co-authored-by: Micah Rosales <mrosales@users.noreply.github.com>
* WIP:add Chinese translation for first steps doc
* add Chinese translation for first steps doc
* improve translations
Co-authored-by: Waynerv <wei.xie@woqutech.com>
* drop model class from additional responses when generating openapi
* ♻️ Copy response to be mutated early in get_openapi_path
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Generated new translation directory to support Italian docs
* ⬆️ Upgrade/pin pytest to >= 5.4.3
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Use ASGI root_path when it is provided and openapi_prefix is empty.
* Strip trailing slashes from root_path.
* Please mypy.
* Fix extending openapi test.
* 📝 Add docs and tutorial for using root_path behind a proxy
* ♻️ Refactor application root_path logic, use root_path, deprecate openapi_prefix
* ✅ Add tests for Behind a Proxy with root_path
* ♻️ Refactor test
* 📝 Update/add docs for Sub-applications and Behind a Proxy
* 📝 Update Extending OpenAPI with openapi_prefix parameter
* ✅ Add test for deprecated openapi_prefix
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* 📝 Update help docs: Gitter, issues, links
also fix Gitter tab padding
* 📝 Update new GitHub issue templates
* 📝 Add note about extra help required for new issues
* 🐛 Fix extra support for enum with its own schema
* ✅ Fix/update test for enum with its own schema
* 🐛 Fix type declarations
* 🔧 Update format and lint scripts to support locally installed Pydantic and Starlette
* 🐛 Add temporary type ignores while enum schemas are merged
* Fixed Typo in [EN] tutorial: body-fields
- remove duplicate of examples text
* ✏️ Re-word and clarify extra info docs
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* ✨ Allow disabling docs UIs by disabling openapi_url
* 📝 Add docs for disabling OpenAPI and docs in prod or other environments
* ✅ Add tests for disabling OpenAPI and docs
* Translate features.md file to Portuguese
* Changes word of features.md translation to Portuguese
* Fixing typos and bad wording
Thanks @Serrones for the kind review
* Spanish translation for the tutorial-user-guide index page
* Improve some parts of the text in terms of writing
* Change the wording to keep the documentation consistent.
* 📝 Add small wording and consistency changes
* 🎨 Apply the same consistency changes to EN 🤷
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Add new language of docs: zh
* Add deployment.md Chinese trans
* add "or"
* rm index.md
* updates Chinese translations of deployement.md
* update translations of deployment.md
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* translation features.md to Chinese
* update review data
* :DOCS: update with review
* 🔥 Remove double link in build mkdocs.yml for other languages
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Update sql-databases alembic docs
Was helpful to refer to the full-stack project when integrating alembic into my own project
* 📝 Update Alembic note in docs
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Implemented response_model_exclude_defaults and response_model_exclude_none to be compatible pydantic options.
* 🚚 Rename and invert include_none to exclude_none to keep in sync with Pydantic
Co-authored-by: Lukas Voegtle <lukas.voegtle@sick.de>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Add an example of setting up a test database.
* 📝 Add/update docs for testing a DB with dependency overrides
* 🔧 Update test script, remove line removing test file as it is removed during testing
* ✅ Update testing coverage pragma
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* ✨ Update settings examples to use lru_cache
* 📝 Update docs for Settings, using @lru_cache
* 🎨 Update lru_cache colors to show difference in stored values
* Add doc and example for env var config
* Syntax highlight for .env file
* Add test for configuration docs
* 📝 Update settings docs, add more examples
* ✅ Add tests for settings
* 🚚 Rename "Application Configuration" to "Metadata and Docs URLs"
to disambiguate between that and settings
* 🔥 Remove replaced example file
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Handle automatic embedding with Depends
* 🐛 Fix body embeds for sub-dependencies and simplify implementation
* ✅ Add/update tests for body embeds in dependencies
* 👷 Trigger Travis
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* Add documentation of example kwarg of Field
* 📝 Update info about schema examples
* 🚚 Move example file to new directory
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* FIX: #894
Include recursion check for create_cloned_field.
Added test for recursive model.
* ♻️ Refactor and format create_cloned_field()
Co-authored-by: Lukas Voegtle <lukas.voegtle@sick.de>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* add example of pycharm in tutorial/debugging.md
* 📝 Update PyCharm debug instructions and screenshot
* 🚚 Move image to new location in docs
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* 🏁 Fix ./scripts/docs.py encoding for Windows
* 🔥 Remove ujson from tests as it prevents Windows development
It's still tested by Starlette anyway
* 📝 Update development instructions for Windows
* 🎨 Update format for WSGIMiddleware example
* ✅ Update tests to run on Windows
* Added new external link
I added an article in which I briefly explain how to build an Apache Kafka producer / consumer with FastAPI and aiokafka.
* 📝 Update format
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
* 🌐 Refactor file structure to support internationalization
* ✅ Update tests changed after i18n
* 🔀 Merge Typer style from master
* 🔧 Update MkConfig with Typer-styles
* 🎨 Format mkdocs.yml with cannonical form
* 🎨 Format mkdocs.yml
* 🔧 Update MkDocs config
* ➕ Add docs translation scripts dependencies
* ✨ Add Typer scripts to handle translations
* ✨ Add missing translation snippet to include
* ✨ Update contributing docs, add docs for translations
* 🙈 Add docs_build to gitignore
* 🔧 Update scripts with new locations and docs scripts
* 👷 Update docs deploy action with translations
* 📝 Add note about languages not supported in the theme
* ✨ Add first translation, for Spanish
* ✨ Re-export main features used from Starlette to simplify developer's code
* ♻️ Refactor Starlette exports
* ♻️ Refactor tutorial examples to use re-exported utils from Starlette
* 📝 Add examples for all middlewares
* 📝 Add new docs for middlewares
* 📝 Add examples for custom responses
* 📝 Extend docs for custom responses
* 📝 Update docs and add notes explaining re-exports from Starlette everywhere
* 🍱 Update screenshot for HTTP status
* 🔧 Update MkDocs config with new content
* ♻️ Refactor tests to use re-exported utils from Starlette
* ✨ Re-export WebSocketDisconnect from Starlette for tests
* ✅ Add extra tests for extra re-exported middleware
* ✅ Add tests for re-exported responses from Starlette
* ✨ Add docs about mounting WSGI apps
* ➕ Add Flask as a dependency to test WSGIMiddleware
* ✅ Test WSGIMiddleware example
Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling questions.
All that, on top of all the incredible help provided by a bunch of community members, the [FastAPI Experts](https://fastapi.tiangolo.com/fastapi-people/#experts), that give a lot of their time to come here and help others.
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many questions, I'll have to discard and close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
- type:checkboxes
id:checks
attributes:
label:First Check
description:Please confirm and check all the following options.
options:
- label:I added a very descriptive title here.
required:true
- label:I used the GitHub search to find a similar question and didn't find it.
required:true
- label:I searched the FastAPI documentation, with the integrated search.
required:true
- label:I already searched in Google "How to X in FastAPI" and didn't find any information.
required:true
- label:I already read and followed all the tutorial in the docs and didn't find an answer.
required:true
- label:I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).
required:true
- label:I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).
required:true
- label:I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).
required:true
- type:checkboxes
id:help
attributes:
label:Commit to Help
description:|
After submitting this, I commit to one of:
* Read open questions until I find 2 where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Review one Pull Request by downloading the code and following [all the review process](https://fastapi.tiangolo.com/help-fastapi/#review-pull-requests).
options:
- label:I commit to help with one of those options 👆
required:true
- type:textarea
id:example
attributes:
label:Example Code
description:|
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
placeholder:|
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
render:python
validations:
required:true
- type:textarea
id:description
attributes:
label:Description
description:|
What is the problem, question, or error?
Write a short description telling me what you are doing, what you expect to happen, and what is currently happening.
placeholder:|
* Open the browser and call the endpoint `/`.
* It returns a JSON with `{"Hello": "World"}`.
* But I expected it to return `{"Hello": "Sara"}`.
validations:
required:true
- type:dropdown
id:os
attributes:
label:Operating System
description:What operating system are you on?
multiple:true
options:
- Linux
- Windows
- macOS
- Other
validations:
required:true
- type:textarea
id:os-details
attributes:
label:Operating System Details
description:You can add more details about your operating system here, in particular if you chose "Other".
about:To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
description:You are @tiangolo or he asked you directly to create an issue here. If not, check the other options. 👇
body:
- type:markdown
attributes:
value:|
Thanks for your interest in FastAPI! 🚀
If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/fastapi/discussions/categories/questions) instead.
- type:checkboxes
id:privileged
attributes:
label:Privileged issue
description:Confirm that you are allowed to create an issue here.
options:
- label:I'm @tiangolo or he asked me directly to create an issue here.
new_translation_message=f"Good news everyone! 😉 There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}. 🎉 This requires 2 approvals from native speakers to be merged. 🤓"
done_translation_message=f"~There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}~ Good job! This is done. 🍰☕"
# Normally only one language, but still
forlanginlangs:
iflangnotinlang_to_discussion_map:
log_message=f"Could not find discussion for language: {lang}"
logging.error(log_message)
raiseRuntimeError(log_message)
discussion=lang_to_discussion_map[lang]
logging.info(
f"Found a translation discussion for language: {lang} in discussion: #{discussion.number}"
)
already_notified_comment:Union[Comment,None]=None
already_done_comment:Union[Comment,None]=None
logging.info(
f"Checking current comments in discussion: #{discussion.number} to see if already notified about this PR: #{pr.number}"
"message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.
The key features are:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
* **Fast to code**: Increase the speed to develop features by about 200% to 300% *.
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
* **Robust**: Get production-ready code. With automatic interactive documentation.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="http://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
<small>* estimation based on tests on an internal development team, building production applications.</small>
## Sponsors
<!-- sponsors -->
<a href="https://cryptapi.io/" target="_blank" title="CryptAPI: Your easy to use, secure and privacy oriented payment gateway."><img src="https://fastapi.tiangolo.com/img/sponsors/cryptapi.svg"></a>
<a href="https://platform.sh/try-it-now/?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023" target="_blank" title="Build, run and scale your apps on a modern, reliable, and secure PaaS."><img src="https://fastapi.tiangolo.com/img/sponsors/platform-sh.png"></a>
<a href="https://www.deta.sh/?ref=fastapi" target="_blank" title="The launchpad for all your (team's) ideas"><img src="https://fastapi.tiangolo.com/img/sponsors/deta.svg"></a>
<a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython.png"></a>
<a href="https://testdriven.io/courses/tdd-fastapi/" target="_blank" title="Learn to build high-quality web apps with best practices"><img src="https://fastapi.tiangolo.com/img/sponsors/testdriven.svg"></a>
<a href="https://github.com/deepset-ai/haystack/" target="_blank" title="Build powerful search from composable, open source building blocks"><img src="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a>
<a href="https://careers.powens.com/" target="_blank" title="Powens is hiring!"><img src="https://fastapi.tiangolo.com/img/sponsors/powens.png"></a>
<a href="https://www.svix.com/" target="_blank" title="Svix - Webhooks as a service"><img src="https://fastapi.tiangolo.com/img/sponsors/svix.svg"></a>
<a href="https://databento.com/" target="_blank" title="Pay as you go for market data"><img src="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a>
"*[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products.*"
"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
"*Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that.*"
"*If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]*"
"*We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]*"
"*We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]*"
"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div>
---
"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._"
If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
## Requirements
Python 3.6+
Python 3.7+
FastAPI stands on the shoulders of giants:
@@ -88,16 +125,28 @@ FastAPI stands on the shoulders of giants:
## Installation
```bash
pip install fastapi
<div class="termy">
```console
$ pip install fastapi
---> 100%
```
You will also need an ASGI server, for production such as <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
</div>
```bash
pip install uvicorn
You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://github.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
@@ -261,13 +326,13 @@ And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" targe
### Recap
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard **Python 3.6+**.
Just standard **Python 3.7+**.
For example, for an `int`:
@@ -318,7 +383,7 @@ Coming back to the previous code example, **FastAPI** will:
* As the `q` parameter is declared with `= None`, it is optional.
* Without the `None` it would be required (as is the body in the case with `PUT`).
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
* Check that it has a required attribute `name` that should be a `str`.
* Check that it has a required attribute `name` that should be a `str`.
* Check that it has a required attribute `price` that has to be a `float`.
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
* All this would also work for deeply nested JSON objects.
@@ -363,10 +428,10 @@ For a more complete example including more features, see the <a href="https://fa
* A very powerful and easy to use **<abbr title="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>** system.
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
* **GraphQL** integration with <a href="https://strawberry.rocks" class="external-link" target="_blank">Strawberry</a> and other libraries.
* Many extra features (thanks to Starlette) as:
* **WebSockets**
* **GraphQL**
* extremely easy tests based on `requests` and `pytest`
* extremely easy tests based on HTTPX and `pytest`
* **CORS**
* **Cookie Sessions**
* ...and more.
@@ -381,25 +446,25 @@ To understand more about it, see the section <a href="https://fastapi.tiangolo.c
Used by Pydantic:
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - for faster JSON <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
* <a href="https://docs.pydantic.dev/latest/usage/pydantic_settings/" target="_blank"><code>pydantic-settings</code></a> - for settings management.
* <a href="https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target="_blank"><code>pydantic-extra-types</code></a> - for extra types to be used with Pydantic.
Used by Starlette:
* <a href="http://docs.python-requests.org" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
* <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <a href="https://www.python-httpx.org" target="_blank"><code>httpx</code></a> - Required if you want to use the `TestClient`.
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
Used by FastAPI / Starlette:
* <a href="http://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
You can install all of these with `pip install fastapi[all]`.
You can install all of these with `pip install "fastapi[all]"`.
Security is very important for FastAPI and its community. 🔒
Learn more about it below. 👇
## Versions
The latest version of FastAPI is supported.
You are encouraged to [write tests](https://fastapi.tiangolo.com/tutorial/testing/) for your application and update your FastAPI version frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**.
You can learn more about [FastAPI versions and how to pin and upgrade them](https://fastapi.tiangolo.com/deployment/versions/) for your project in the docs.
## Reporting a Vulnerability
If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue.
I (the author, [@tiangolo](https://twitter.com/tiangolo)) will review it thoroughly and get back to you.
## Public Discussions
Please restrain from publicly discussing a potential security vulnerability. 🙊
It's better to discuss privately and try to find a solution first, to limit the potential impact as much as possible.
By default, **FastAPI** will return the responses using Starlette's `JSONResponse`, putting the content you return from your *path operation* inside of that `JSONResponse`.
It will use the default status code or the one you set in your *path operation*.
## Additional status codes
If you want to return additional status codes apart from the main one, you can do that by returning a `Response` directly, like a `JSONResponse`, and set the additional status code directly.
For example, let's say that you want to have a *path operation* that allows to update items, and returns HTTP status codes of 200 "OK" when successful.
But you also want it to accept new items. And when the items didn't exist before, it creates them, and returns an HTTP status code of 201 "Created".
To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want:
```Python hl_lines="2 20"
{!./src/additional_status_codes/tutorial001.py!}
```
!!! warning
When you return a `Response` directly, like in the example above, it will be returned directly.
It won't be serialized with a model, etc.
Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`).
## OpenAPI and API docs
If you return additional status codes and responses directly, they won't be included in the OpenAPI schema (the API docs), because FastAPI doesn't have a way to know before hand what you are going to return.
But you can document that in your code, using: [Additional Responses](additional-responses.md){.internal-link target=_blank}.
If you are starting with **FastAPI**, you might not need this.
By default, **FastAPI** will return the responses using Starlette's `JSONResponse`.
You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}.
But if you return a `Response` directly, the data won't be automatically converted, and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type`).
But you can also declare the `Response` that you want to be used, in the *path operation decorator*.
The contents that you return from your *path operation function* will be put inside of that `Response`.
And if that `Response` has a JSON media type (`application/json`), like is the case with the `JSONResponse` and `UJSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*.
!!! note
If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.
## Use `UJSONResponse`
For example, if you are squeezing performance, you can install and use `ujson` and set the response to be Starlette's `UJSONResponse`.
Import the `Response` class (sub-class) you want to use and declare it in the *path operation decorator*.
```Python hl_lines="2 7"
{!./src/custom_response/tutorial001.py!}
```
!!! note
Notice that you import it directly from `starlette.responses`, not from `fastapi`.
!!! info
The parameter `response_class` will also be used to define the "media type" of the response.
In this case, the HTTP header `Content-Type` will be set to `application/json`.
And it will be documented as such in OpenAPI.
## HTML Response
To return a response with HTML directly from **FastAPI**, use `HTMLResponse`.
* Import `HTMLResponse`.
* Pass `HTMLResponse` as the parameter `content_type` of your *path operation*.
```Python hl_lines="2 7"
{!./src/custom_response/tutorial002.py!}
```
!!! note
Notice that you import it directly from `starlette.responses`, not from `fastapi`.
!!! info
The parameter `response_class` will also be used to define the "media type" of the response.
In this case, the HTTP header `Content-Type` will be set to `text/html`.
And it will be documented as such in OpenAPI.
### Return a Starlette `Response`
As seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}, you can also override the response directly in your *path operation*, by returning it.
The same example from above, returning an `HTMLResponse`, could look like:
```Python hl_lines="2 7 19"
{!./src/custom_response/tutorial003.py!}
```
!!! warning
A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs.
!!! info
Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object your returned.
### Document in OpenAPI and override `Response`
If you want to override the response from inside of the function but at the same time document the "media type" in OpenAPI, you can use the `response_class` parameter AND return a `Response` object.
The `response_class` will then be used only to document the OpenAPI *path operation*, but your `Response` will be used as is.
#### Return an `HTMLResponse` directly
For example, it could be something like:
```Python hl_lines="7 23 21"
{!./src/custom_response/tutorial004.py!}
```
In this example, the function `generate_html_response()` already generates a Starlette `Response` instead of the HTML in a `str`.
By returning the result of calling `generate_html_response()`, you are already returning a `Response` that will override the default **FastAPI** behavior.
But as you passed the `HTMLResponse` in the `response_class`, **FastAPI** will know how to document it in OpenAPI and the interactive docs as HTML with `text/html`:
You can also declare the media type and many other details in OpenAPI using `responses`: [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
You can define event handlers (functions) that need to be executed before the application starts up, or when the application is shutting down.
These functions can be declared with `async def` or normal `def`.
## `startup` event
To add a function that should be run before the application starts, declare it with the event `"startup"`:
```Python hl_lines="8"
{!./src/events/tutorial001.py!}
```
In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values.
You can add more than one event handler function.
And your application won't start receiving requests until all the `startup` event handlers have completed.
## `shutdown` event
To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`:
```Python hl_lines="6"
{!./src/events/tutorial002.py!}
```
Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`.
!!! info
In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents.
!!! tip
Notice that in this case we are using a standard Python `open()` function that interacts with a file.
So, it involves I/O (input/output), that requires "waiting" for things to be written to disk.
But `open()` doesn't use `async` and `await`.
So, we declare the event handler function with standard `def` instead of `async def`.
!!! info
You can read more about these event handlers in <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette's Events' docs</a>.
**FastAPI** has optional support for GraphQL (provided by Starlette directly), using the `graphene` library.
You can combine normal FastAPI *path operations* with GraphQL on the same application.
## Import and use `graphene`
GraphQL is implemented with Graphene, you can check <a href="https://docs.graphene-python.org/en/latest/quickstart/" class="external-link" target="_blank">Graphene's docs</a> for more details.
Import `graphene` and define your GraphQL data:
```Python hl_lines="1 6 7 8 9 10"
{!./src/graphql/tutorial001.py!}
```
## Add Starlette's `GraphQLApp`
Then import and add Starlette's `GraphQLApp`:
```Python hl_lines="3 14"
{!./src/graphql/tutorial001.py!}
```
!!! info
Here we are using `.add_route`, that is the way to add a route in Starlette (inherited by FastAPI) without declaring the specific operation (as would be with `.get()`, `.post()`, etc).
## Check it
Run it with Uvicorn and open your browser at <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000</a>.
You will see GraphiQL web user interface:
<img src="/img/tutorial/graphql/image01.png">
## More details
For more details, including:
* Accessing request information
* Adding background tasks
* Using normal or async functions
check the official <a href="https://www.starlette.io/graphql/" class="external-link" target="_blank">Starlette GraphQL docs</a>.
### Using the *path operation function* name as the operationId
If you want to use your APIs' function names as `operationId`s, you can iterate over all of them and override each *path operation's* `operation_id` using their `APIRoute.name`.
You should do it after adding all your *path operations*.
If you manually call `app.openapi()`, you should update the `operationId`s before that.
!!! warning
If you do this, you have to make sure each one of your *path operation functions* has a unique name.
Even if they are in different modules (Python files).
## Exclude from OpenAPI
To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`;
There are at least two situations where you could need to create your **FastAPI** application using some specific paths.
But then you need to set them up to be served with a path prefix.
It could happen if you have a:
* **Proxy** server.
* You are "**mounting**" a FastAPI application inside another FastAPI application (or inside another ASGI application, like Starlette).
## Proxy
Having a proxy in this case means that you could declare a path at `/app`, but then, you could need to add a layer on top (the Proxy) that would put your **FastAPI** application under a path like `/api/v1`.
In this case, the original path `/app` will actually be served at `/api/v1/app`.
Even though your application "thinks" it is serving at `/app`.
And the Proxy could be re-writing the path "on the fly" to keep your application convinced that it is serving at `/app`.
Up to here, everything would work as normally.
But then, when you open the integrated docs, they would expect to get the OpenAPI schema at `/openapi.json`, instead of `/api/v1/openapi.json`.
So, the frontend (that runs in the browser) would try to reach `/openapi.json` and wouldn't be able to get the OpenAPI schema.
So, it's needed that the frontend looks for the OpenAPI schema at `/api/v1/openapi.json`.
And it's also needed that the returned JSON OpenAPI schema has the defined path at `/api/v1/app` (behind the proxy) instead of `/app`.
---
For these cases, you can declare an `openapi_prefix` parameter in your `FastAPI` application.
See the section below, about "mounting", for an example.
## Mounting a **FastAPI** application
"Mounting" means adding a complete "independent" application in a specific path, that then takes care of handling all the sub-paths.
You could want to do this if you have several "independent" applications that you want to separate, having their own independent OpenAPI schema and user interfaces.
### Top-level application
First, create the main, top-level, **FastAPI** application, and its *path operations*:
```Python hl_lines="3 6 7 8"
{!./src/sub_applications/tutorial001.py!}
```
### Sub-application
Then, create your sub-application, and its *path operations*.
This sub-application is just another standard FastAPI application, but this is the one that will be "mounted".
When creating the sub-application, use the parameter `openapi_prefix`. In this case, with a prefix of `/subapi`:
```Python hl_lines="11 14 15 16"
{!./src/sub_applications/tutorial001.py!}
```
### Mount the sub-application
In your top-level application, `app`, mount the sub-application, `subapi`.
Here you need to make sure you use the same path that you used for the `openapi_prefix`, in this case, `/subapi`:
```Python hl_lines="11 19"
{!./src/sub_applications/tutorial001.py!}
```
## Check the automatic API docs
Now, run `uvicorn`, if your file is at `main.py`, it would be:
```bash
uvicorn main:app --reload
```
And open the docs at <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
You will see the automatic API docs for the main app, including only its own paths:
And then, open the docs for the sub-application, at <a href="http://127.0.0.1:8000/subapi/docs" class="external-link" target="_blank">http://127.0.0.1:8000/subapi/docs</a>.
You will see the automatic API docs for the sub-application, including only its own sub-paths, with their correct prefix:
If you try interacting with any of the two user interfaces, they will work, because the browser will be able to talk to the correct path (or sub-path).
You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API" class="external-link" target="_blank">WebSockets</a> with **FastAPI**.
## WebSockets client
### In production
In your production system, you probably have a frontend created with a modern framework like React, Vue.js or Angular.
And to communicate using WebSockets with your backend you would probably use your frontend's utilities.
Or you might have a native mobile application that communicates with your WebSocket backend directly, in native code.
Or you might have any other way to communicate with the WebSocket endpoint.
---
But for this example, we'll use a very simple HTML document with some JavaScript, all inside a long string.
This, of course, is not optimal and you wouldn't use it for production.
In production you would have one of the options above.
But it's the simplest way to focus on the server-side of WebSockets and have a working example:
In a WebSocket it doesn't really make sense to raise an `HTTPException`. So it's better to close the WebSocket connection directly.
You can use a closing code from the <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1" class="external-link" target="_blank">valid codes defined in the specification</a>.
In the future, there will be a `WebSocketException` that you will be able to `raise` from anywhere, and add exception handlers for it. It depends on the <a href="https://github.com/encode/starlette/pull/527" class="external-link" target="_blank">PR #527</a> in Starlette.
## More info
To learn more about the options, check Starlette's documentation for:
First, you might want to see the basic ways to [help FastAPI and get help](help-fastapi.md){.internal-link target=_blank}.
## Developing
If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment.
### Virtual environment with `venv`
You can create a virtual environment in a directory using Python's `venv` module:
```console
$ python -m venv env
```
That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment.
### Activate the environment
Activate the new environment with:
```console
$source ./env/bin/activate
```
Or in Windows' PowerShell:
```console
$ .\env\Scripts\Activate.ps1
```
Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
```console
$source ./env/Scripts/activate
```
To check it worked, use:
```console
$ which pip
some/directory/fastapi/env/bin/pip
```
If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉
Or in Windows PowerShell:
```console
$ Get-Command pip
some/directory/fastapi/env/bin/pip
```
!!! tip
Every time you install a new package with `pip` under that environment, activate the environment again.
This makes sure that if you use a terminal program installed by that package (like `flit`), you use the one from your local environment and not any other that could be installed globally.
### Flit
**FastAPI** uses <a href="https://flit.readthedocs.io/en/latest/index.html" class="external-link" target="_blank">Flit</a> to build, package and publish the project.
After activating the environment as described above, install `flit`:
```console
$ pip install flit
```
Now re-activate the environment to make sure you are using the `flit` you just installed (and not a global one).
And now use `flit` to install the development dependencies:
```console
$ flit install --deps develop --symlink
```
It will install all the dependencies and your local FastAPI in your local environment.
#### Using your local FastAPI
If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code.
And if you update that local FastAPI source code, as it is installed with `--symlink`, when you run that Python file again, it will use the fresh version of FastAPI you just edited.
That way, you don't have to "install" your local version to be able to test every change.
### Format
There is a script that you can run that will format and clean all your code:
```console
$ bash scripts/format.sh
```
It will also auto-sort all your imports.
For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above:
```console
$ flit install --symlink
```
### Format imports
There is another script that formats all the imports and makes sure you don't have unused imports:
```console
$ bash scripts/format-imports.sh
```
As it runs one command after the other and modifies and reverts many files, it takes a bit longer to run, so it might be easier to use `scripts/format.sh` frequently and `scripts/format-imports.sh` only before committing.
## Docs
The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>.
All the documentation is in Markdown format in the directory `./docs`.
Many of the tutorials have blocks of code.
In most of the cases, these blocks of code are actual complete applications that can be run as is.
In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs/src/` directory.
And those Python files are included/injected in the documentation when generating the site.
### Docs for tests
Most of the tests actually run against the example source files in the documentation.
This helps making sure that:
* The documentation is up to date.
* The documentation examples can be run as is.
* Most of the features are covered by the documentation, ensured by test coverage.
During local development, there is a script that builds the site and checks for any changes, live-reloading:
```console
$ bash scripts/docs-live.sh
```
It will serve the documentation on `http://0.0.0.0:8008`.
That way, you can edit the documentation/source files and see the changes live.
### Apps and docs at the same time
If you run the examples with, e.g.:
```console
$ uvicorn tutorial001:app --reload
```
as Uvicorn by default will use the port `8000`, the documentation on port `8008` won't clash.
## Tests
There is a script that you can run locally to test all the code and generate coverage reports in HTML:
```console
$ bash scripts/test-cov-html.sh
```
This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.
### Tests in your editor
If you want to use the integrated tests in your editor add `./docs/src` to your `PYTHONPATH` variable.
For example, in VS Code you can create a file `.env` with:
* <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a> für API-Erstellung, zusammen mit Deklarationen von <abbr title="auch genannt: Endpunkte, Routen">Pfad</abbr> <abbr title="gemeint sind: HTTP-Methoden, wie POST, GET, PUT, DELETE">Operationen</abbr>, Parameter, Nachrichtenrumpf-Anfragen (englisch: body request), Sicherheit, etc.
* Automatische Dokumentation der Datenentitäten mit dem <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> (OpenAPI basiert selber auf dem JSON Schema).
* Entworfen auf Grundlage dieser Standards nach einer sorgfältigen Studie, statt einer nachträglichen Schicht über diesen Standards.
* Dies ermöglicht automatische **Quellcode-Generierung auf Benutzerebene** in vielen Sprachen.
### Automatische Dokumentation
Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzerschnittstellen. Da FastAPI auf OpenAPI basiert, gibt es hierzu mehrere Optionen, wobei zwei standardmäßig vorhanden sind.
* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank"><strong>Swagger UI</strong></a>, bietet interaktive Exploration: testen und rufen Sie ihre API direkt vom Webbrowser auf.
Alles basiert auf **Python 3.6 Typ**-Deklarationen (dank Pydantic). Es muss keine neue Syntax gelernt werden, nur standardisiertes modernes Python.
Wenn Sie eine kurze, zweiminütige, Auffrischung in der Benutzung von Python Typ-Deklarationen benötigen (auch wenn Sie FastAPI nicht nutzen), schauen Sie sich diese kurze Einführung an (Englisch): Python Types{.internal-link target=_blank}.
Sie schreiben Standard-Python mit Typ-Deklarationen:
```Python
fromtypingimportList,Dict
fromdatetimeimportdate
frompydanticimportBaseModel
# Deklariere eine Variable als str
# und bekomme Editor-Unterstütung innerhalb der Funktion
Übergebe die Schlüssel und die zugehörigen Werte des `second_user_data` Datenwörterbuches direkt als Schlüssel-Wert Argumente, äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`
### Editor Unterstützung
FastAPI wurde so entworfen, dass es einfach und intuitiv zu benutzen ist; alle Entscheidungen wurden auf mehreren Editoren getestet (sogar vor der eigentlichen Implementierung), um so eine best mögliche Entwicklererfahrung zu gewährleisten.
In der letzen Python Entwickler Umfrage stellte sich heraus, dass <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">die meist genutzte Funktion die "Autovervollständigung" ist</a>.
Die gesamte Struktur von **FastAPI** soll dem gerecht werden. Autovervollständigung funktioniert überall.
Sie müssen selten in die Dokumentation schauen.
So kann ihr Editor Sie unterstützen:
* in <a href="https://code.visualstudio.com/" class="external-link" target="_blank">Visual Studio Code</a>:
Sie bekommen Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price` Schlüssel aus einem JSON Datensatz (dieser könnte auch verschachtelt sein) aus einer Anfrage.
Hierdurch werden Sie nie wieder einen falschen Schlüsselnamen benutzen und sparen sich lästiges Suchen in der Dokumentation, um beispielsweise herauszufinden ob Sie `username` oder `user_name` als Schlüssel verwenden.
### Kompakt
FastAPI nutzt für alles sensible **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen.
Aber standardmäßig, **"funktioniert einfach"** alles.
### Validierung
* Validierung für die meisten (oder alle?) Python **Datentypen**, hierzu gehören:
* JSON Objekte (`dict`).
* JSON Listen (`list`), die den Typ ihrer Elemente definieren.
* Zeichenketten (`str`), mit definierter minimaler und maximaler Länge.
* Zahlen (`int`, `float`) mit minimaler und maximaler Größe, usw.
* Validierung für ungewöhnliche Typen, wie:
* URL.
* Email.
* UUID.
* ... und andere.
Die gesamte Validierung übernimmt das etablierte und robuste **Pydantic**.
### Sicherheit und Authentifizierung
Integrierte Sicherheit und Authentifizierung. Ohne Kompromisse bei Datenbanken oder Datenmodellen.
Unterstützt werden alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören:
* HTTP Basis Authentifizierung.
* **OAuth2** (auch mit **JWT Zugriffstokens**). Schauen Sie sich hierzu dieses Tutorial an: [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.
* API Schlüssel in:
* Kopfzeile (HTTP Header).
* Anfrageparametern.
* Cookies, etc.
Zusätzlich gibt es alle Sicherheitsfunktionen von Starlette (auch **session cookies**).
Alles wurde als wiederverwendbare Werkzeuge und Komponenten geschaffen, die einfach in ihre Systeme, Datenablagen, relationale und nicht-relationale Datenbanken, ..., integriert werden können.
### Einbringen von Abhängigkeiten (meist: Dependency Injection)
FastAPI enthält ein extrem einfaches, aber extrem mächtiges <abbr title='oft verwendet im Zusammenhang von: Komponenten, Resourcen, Diensten, Dienstanbieter'><strong>Dependency Injection</strong></abbr> System.
* Selbst Abhängigkeiten können Abhängigkeiten haben, woraus eine Hierachie oder ein **"Graph" von Abhängigkeiten** entsteht.
* **Automatische Umsetzung** durch FastAPI.
* Alle abhängigen Komponenten könnten Daten von Anfragen, **Erweiterungen der Pfadoperations-**Einschränkungen und der automatisierten Dokumentation benötigen.
* **Automatische Validierung** selbst für *Pfadoperationen*-Parameter, die in den Abhängigkeiten definiert wurden.
* **Keine Kompromisse** bei Datenbanken, Eingabemasken, usw. Sondern einfache Integration von allen.
### Unbegrenzte Erweiterungen
Oder mit anderen Worten, sie werden nicht benötigt. Importieren und nutzen Sie Quellcode nach Bedarf.
Jede Integration wurde so entworfen, dass sie einfach zu nutzen ist (mit Abhängigkeiten), sodass Sie eine Erweiterung für Ihre Anwendung mit nur zwei Zeilen an Quellcode implementieren können. Hierbei nutzen Sie die selbe Struktur und Syntax, wie bei Pfadoperationen.
### Getestet
* 100% <abbr title="Die Anzahl an Code, die automatisch getestet wird">Testabdeckung</abbr>.
* 100% <abbr title="Python Typ Annotationen, mit dennen Ihr Editor und andere exteren Werkezuge Sie besser unterstützen können">Typen annotiert</abbr>.
* Verwendet in Produktionsanwendungen.
## Starlette's Merkmale
**FastAPI** ist vollkommen kompatibel (und basiert auf) <a href="https://www.starlette.io/" class="external-link" target="_blank"><strong>Starlette</strong></a>. Das bedeutet, auch ihr eigener Starlette Quellcode funktioniert.
`FastAPI` ist eigentlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, können Sie das meiste Ihres Wissens direkt anwenden.
Mit **FastAPI** bekommen Sie viele von **Starlette**'s Funktionen (da FastAPI nur Starlette auf Steroiden ist):
* Stark beeindruckende Performanz. Es ist <a href="https://github.com/encode/starlette#performance" class="external-link" target="_blank">eines der schnellsten Python Frameworks, auf Augenhöhe mit **NodeJS** und **Go**</a>.
**FastAPI** ist vollkommen kompatibel (und basiert auf) <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>. Das bedeutet, auch jeder zusätzliche Pydantic Quellcode funktioniert.
Verfügbar sind ebenso externe auf Pydantic basierende Bibliotheken, wie <abbr title="Object-Relational Mapper (Abbildung von Objekten auf relationale Strukturen)">ORM</abbr>s, <abbr title="Object-Document Mapper (Abbildung von Objekten auf nicht-relationale Strukturen)">ODM</abbr>s für Datenbanken.
Daher können Sie in vielen Fällen das Objekt einer Anfrage **direkt zur Datenbank** schicken, weil alles automatisch validiert wird.
Das selbe gilt auch für die andere Richtung: Sie können jedes Objekt aus der Datenbank **direkt zum Klienten** schicken.
Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für die gesamte Datenverarbeitung Pydantic nutzt):
* **Kein Kopfzerbrechen**:
* Sie müssen keine neue Schemadefinitionssprache lernen.
* Wenn Sie mit Python's Typisierung arbeiten können, können Sie auch mit Pydantic arbeiten.
* Gutes Zusammenspiel mit Ihrer/Ihrem **<abbr title="Integrierten Entwicklungsumgebung, ähnlich zu (Quellcode-)Editor">IDE</abbr>/<abbr title="Ein Programm, was Fehler im Quellcode sucht">linter</abbr>/Gehirn**:
* Weil Datenstrukturen von Pydantic einfach nur Instanzen ihrer definierten Klassen sind, sollten Autovervollständigung, Linting, mypy und ihre Intuition einwandfrei funktionieren.
* **Schnell**:
* In <a href="https://pydantic-docs.helpmanual.io/benchmarks/" class="external-link" target="_blank">Vergleichen</a> ist Pydantic schneller als jede andere getestete Bibliothek.
* Validierung von **komplexen Strukturen**:
* Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc.
* Validierungen erlauben eine klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema.
* Sie können stark **verschachtelte JSON** Objekte haben und diese sind trotzdem validiert und annotiert.
* **Erweiterbar**:
* Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator` dekorierten Methode erweitern.
You can use <a href="https://www.docker.com/" class="external-link" target="_blank">**Docker**</a> for deployment. It has several advantages like security, replicability, development simplicity, etc.
In this section you'll see instructions and links to guides to know how to:
* Make your **FastAPI** application a Docker image/container with maximum performance. In about **5 min**.
* (Optionally) understand what you, as a developer, need to know about HTTPS.
* Set up a Docker Swarm mode cluster with automatic HTTPS, even on a simple $5 USD/month server. In about **20 min**.
* Generate and deploy a full **FastAPI** application, using your Docker Swarm cluster, with HTTPS, etc. In about **10 min**.
---
You can also easily use **FastAPI** in a standard server directly too (without Docker).
## Docker
If you are using Docker, you can use the official Docker image:
This image has an "auto-tuning" mechanism included, so that you can just add your code and get very high performance automatically. And without making sacrifices.
But you can still change and update all the configurations with environment variables or configuration files.
!!! tip
To see all the configurations and options, go to the Docker image page: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
### Create a `Dockerfile`
* Go to your project directory.
* Create a `Dockerfile` with:
```Dockerfile
FROMtiangolo/uvicorn-gunicorn-fastapi:python3.7
COPY ./app /app
```
#### Bigger Applications
If you followed the section about creating [Bigger Applications with Multiple Files](tutorial/bigger-applications.md){.internal-link target=_blank}, your `Dockerfile` might instead look like:
```Dockerfile
FROMtiangolo/uvicorn-gunicorn-fastapi:python3.7
COPY ./app /app/app
```
#### Raspberry Pi and other architectures
If you are running Docker in a Raspberry Pi (that has an ARM processor) or any other architecture, you can create a `Dockerfile` from scratch, based on a Python base image (that is multi-architecture) and use Uvicorn alone.
* Go to the project directory (in where your `Dockerfile` is, containing your `app` directory).
* Build your FastAPI image:
```bash
docker build -t myimage .
```
### Start the Docker container
* Run a container based on your image:
```bash
docker run -d --name mycontainer -p 80:80 myimage
```
Now you have an optimized FastAPI server in a Docker container. Auto-tuned for your current server (and number of CPU cores).
### Check it
You should be able to check it in your Docker container's URL, for example: <a href="http://192.168.99.100/items/5?q=somequery" class="external-link" target="_blank">http://192.168.99.100/items/5?q=somequery</a> or <a href="http://127.0.0.1/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1/items/5?q=somequery</a> (or equivalent, using your Docker host).
You will see something like:
```JSON
{"item_id":5,"q":"somequery"}
```
### Interactive API docs
Now you can go to <a href="http://192.168.99.100/docs" class="external-link" target="_blank">http://192.168.99.100/docs</a> or <a href="http://127.0.0.1/docs" class="external-link" target="_blank">http://127.0.0.1/docs</a> (or equivalent, using your Docker host).
You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
And you can also go to <a href="http://192.168.99.100/redoc" class="external-link" target="_blank">http://192.168.99.100/redoc</a> or <a href="http://127.0.0.1/redoc" class="external-link" target="_blank">http://127.0.0.1/redoc</a> (or equivalent, using your Docker host).
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
It is easy to assume that HTTPS is something that is just "enabled" or not.
But it is way more complex than that.
!!! tip
If you are in a hurry or don't care, continue with the next section for step by step instructions to set everything up.
To learn the basics of HTTPS, from a consumer perspective, check <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
Now, from a developer's perspective, here are several things to have in mind while thinking about HTTPS:
* For HTTPS, the server needs to have "certificates" generated by a third party.
* Those certificates are actually acquired from the third-party, not "generated".
* Certificates have a lifetime.
* They expire.
* And then they need to be renewed, acquired again from the third party.
* The encryption of the connection happens at the TCP level.
* That's one layer below HTTP.
* So, the certificate and encryption handling is done before HTTP.
* TCP doesn't know about "domains". Only about IP addresses.
* The information about the specific domain requested goes in the HTTP data.
* The HTTPS certificates "certify" a certain domain, but the protocol and encryption happen at the TCP level, before knowing which domain is being dealt with.
* By default, that would mean that you can only have one HTTPS certificate per IP address.
* No matter how big your server is or how small each application you have on it might be.
* There is a solution to this, however.
* There's an extension to the TLS protocol (the one handling the encryption at the TCP level, before HTTP) called <a href="https://en.wikipedia.org/wiki/Server_Name_Indication" class="external-link" target="_blank"><abbr title="Server Name Indication">SNI</abbr></a>.
* This SNI extension allows one single server (with a single IP address) to have several HTTPS certificates and serve multiple HTTPS domains/applications.
* For this to work, a single component (program) running on the server, listening on the public IP address, must have all the HTTPS certificates in the server.
* After obtaining a secure connection, the communication protocol is still HTTP.
* The contents are encrypted, even though they are being sent with the HTTP protocol.
It is a common practice to have one program/HTTP server running on the server (the machine, host, etc.) and managing all the HTTPS parts : sending the decrypted HTTP requests to the actual HTTP application running in the same server (the **FastAPI** application, in this case), take the HTTP response from the application, encrypt it using the appropriate certificate and sending it back to the client using HTTPS. This server is often called a <a href="https://en.wikipedia.org/wiki/TLS_termination_proxy" class="external-link" target="_blank">TLS Termination Proxy</a>.
### Let's Encrypt
Before Let's Encrypt, these HTTPS certificates were sold by trusted third-parties.
The process to acquire one of these certificates used to be cumbersome, require quite some paperwork and the certificates were quite expensive.
But then <a href="https://letsencrypt.org/" class="external-link" target="_blank">Let's Encrypt</a> was created.
It is a project from the Linux Foundation. It provides HTTPS certificates for free. In an automated way. These certificates use all the standard cryptographic security, and are short lived (about 3 months), so the security is actually better because of their reduced lifespan.
The domains are securely verified and the certificates are generated automatically. This also allows automating the renewal of these certificates.
The idea is to automate the acquisition and renewal of these certificates, so that you can have secure HTTPS, for free, forever.
### Traefik
<a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a> is a high performance reverse proxy / load balancer. It can do the "TLS Termination Proxy" job (apart from other features).
It has integration with Let's Encrypt. So, it can handle all the HTTPS parts, including certificate acquisition and renewal.
It also has integrations with Docker. So, you can declare your domains in each application configurations and have it read those configurations, generate the HTTPS certificates and serve HTTPS to your application automatically, without requiring any change in its configuration.
---
With this information and tools, continue with the next section to combine everything.
## Docker Swarm mode cluster with Traefik and HTTPS
You can have a Docker Swarm mode cluster set up in minutes (about 20 min) with a main Traefik handling HTTPS (including certificate acquisition and renewal).
By using Docker Swarm mode, you can start with a "cluster" of a single machine (it can even be a $5 USD / month server) and then you can grow as much as you need adding more servers.
To set up a Docker Swarm Mode cluster with Traefik and HTTPS handling, follow this guide:
### <a href="https://medium.com/@tiangolo/docker-swarm-mode-and-traefik-for-a-https-cluster-20328dba6232" class="external-link" target="_blank">Docker Swarm Mode and Traefik for an HTTPS cluster</a>
### Deploy a FastAPI application
The easiest way to set everything up, would be using the [**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}.
It is designed to be integrated with this Docker Swarm cluster with Traefik and HTTPS described above.
You can generate a project in about 2 min.
The generated project has instructions to deploy it, doing it takes another 2 min.
## Alternatively, deploy **FastAPI** without Docker
You can deploy **FastAPI** directly without Docker too.
You just need to install an ASGI compatible server like:
* <a href="https://www.uvicorn.org/" class="external-link" target="_blank">Uvicorn</a>, a lightning-fast ASGI server, built on uvloop and httptools.
```bash
pip install uvicorn
```
* <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2.
```bash
pip install hypercorn
```
...or any other ASGI server.
And run your application the same way you have done in the tutorials, but without the `--reload` option, e.g.:
```bash
uvicorn main:app --host 0.0.0.0 --port 80
```
or with Hypercorn:
```bash
hypercorn main:app --bind 0.0.0.0:80
```
You might want to set up some tooling to make sure it is restarted automatically if it stops.
You might also want to install <a href="https://gunicorn.org/" class="external-link" target="_blank">Gunicorn</a> and <a href="https://www.uvicorn.org/#running-with-gunicorn" class="external-link" target="_blank">use it as a manager for Uvicorn</a>, or use Hypercorn with multiple workers.
Making sure to fine-tune the number of workers, etc.
But if you are doing all that, you might just use the Docker image that does it automatically.
🛠️ 🩺 ⚙️ **🦁 🎚** & **📄**, & 🔠 👈 💪 🕸 & 🎚 📁.
🔢, 👈 📁 🍦 ⚪️➡️ <abbr title="Content Delivery Network: A service, normally composed of several servers, that provides static files, like JavaScript and CSS. It's commonly used to serve those files from the server closer to the client, improving performance.">💲</abbr>.
**FastAPI** 💪 🛠️ ⏮️ 🙆 <abbr title="Distributed database (Big Data), also 'Not Only SQL'">☁</abbr>.
📥 👥 🔜 👀 🖼 ⚙️ **<a href="https://www.couchbase.com/" class="external-link" target="_blank">🗄</a>**, <abbr title="Document here refers to a JSON object (a dict), with keys and values, and those values can also be other JSON objects, arrays (lists), numbers, strings, booleans, etc.">📄</abbr> 🧢 ☁ 💽.
, 🗄 👍 🚫 ⚙️ 👁 `Bucket` 🎚 💗 "<abbr title="A sequence of code being executed by the program, while at the same time, or at intervals, there can be others being executed too.">🧵</abbr>Ⓜ",, 👥 💪 🤚 🥡 🔗 & 🚶♀️ ⚫️ 👆 🚙 🔢:
* 🤾 🎆 ⏮️ 👆 **<abbr title="Integrated Development Environment, similar to a code editor">💾</abbr>/<abbr title="A program that checks for code errors">🧶</abbr>/🧠**:
🕰 👤 ▶️ 🏗 **FastAPI** ⚫️, 🏆 🍖 ⏪ 🥉, 🔧 🔬, 📄 & 🧰 🔜, & 💡 🔃 🐩 & 🔧 🆑 & 🍋.
## 🔮
👉 ☝, ⚫️ ⏪ 🆑 👈 **FastAPI** ⏮️ 🚮 💭 ➖ ⚠ 📚 👫👫.
⚫️ 💆♂ 👐 🤭 ⏮️ 🎛 ♣ 📚 ⚙️ 💼 👍.
📚 👩💻 & 🏉 ⏪ 🪀 🔛 **FastAPI** 👫 🏗 (🔌 👤 & 👇 🏉).
✋️, 📤 📚 📈 & ⚒ 👟.
**FastAPI** ✔️ 👑 🔮 ⤴️.
& [👆 ℹ](help-fastapi.md){.internal-link target=_blank} 📉 👍.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.