* ➕ 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 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 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
* ♻️ Refactor parts that use optional requirements to make them compatible with installations without them
* ♻️ Update JSON Schema for email field without email-validator installed
* ♻️ 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
* 👷 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
* WIP
* ✨ 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>
* 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
* Make compatible with pydantic v1
* Remove unused import
* Remove unused ignores
* Update pydantic version
* Fix minor formatting issue
* ⏪ Revert removing iterate_in_threadpool
* ✨ Add backwards compatibility with Pydantic 0.32.2
with deprecation warnings
* ✅ Update tests to not break when using Pydantic < 1.0.0
* 📝 Update docs for Pydantic version 1.0.0
* 📌 Update Pydantic range version to support from 0.32.2
* 🎨 Format test imports
* ✨ Add support for Pydantic < 1.2 for populate_validators
* ✨ Add backwards compatibility for Pydantic < 1.2.0 with required fields
* 📌 Relax requirement for Pydantic to < 2.0.0 🎉🚀
* 💚 Update pragma coverage for older Pydantic versions
* ➕ Add development/testing dependencies for Python 3.6
* ✨ Add concurrency submodule with contextmanager_in_threadpool
* ✨ Add AsyncExitStack to ASGI scope in FastAPI app call
* ✨ Use async stack for contextmanager-able dependencies
including running in threadpool sync dependencies
* ✅ Add tests for contextmanager dependencies
including internal raise checks when exceptions should be handled and when not
* ✅ Add test for fake asynccontextmanager raiser
* 🐛 Fix mypy errors and coverage
* 🔇 Remove development logs and prints
* ✅ Add tests for sub-contextmanagers, background tasks, and sync functions
* 🐛 Fix mypy errors for Python 3.7
* 💬 Fix error texts for clarity
* 📝 Add docs for dependencies with yield
* ✨ Update SQL with SQLAlchemy tutorial to use dependencies with yield
and add an alternative with a middleware (from the old tutorial)
* ✅ Update SQL tests to remove DB file during the same tests
* ✅ Add tests for example with middleware
as a copy from the tests with dependencies with yield, removing the DB in the tests
* ✏️ Fix typos with suggestions from code review
Co-Authored-By: dmontagu <35119617+dmontagu@users.noreply.github.com>
This allows using parameters that can have defaults (e.g. `None`) that can be used as query parameters.
But can also be used in routers with that include those parameters as part of the path.
* Add support for strings and __future__ annotations
* Add comments indicating reason for string annotations
* Fix ignores (including removing some unused ignores)
* 🏗️ Implement unique IDs for dynamic models
like those used for composite bodies and responses. IDs based on path (not only on function name, as it can be duplicated in a different module).
* ✅ Add tests for same function name and composite body
* ✅ Update OpenAPI in tests with new dynamic model ID generation
* 🔥 Remove Pipfile.lock
Being a library, it should work independent of locking of dependency tree.
The Pipfile (and Pipfile.lock) is only used locally for development of FastAPI itself, it doesn't affect final users (that is controlled with pyproject.toml).
The Pipfile.lock adds unnecessary noise to PRs that update/upgrade development packages, and the locking is not the same in all environments (e.g. Linux, Mac, and Windows).
Each FastAPI contributor (developing FastAPI itself) can have his/her own Pipfile.lock, but it doesn't have to be in git.
* 🙈 Add Pipfile.lock to .gitignore
* ✨ Implement support for Pydantic's ORM mode
* 🏗️ Re-structure/augment SQL tutorial source using ORM mode
* 📝 Update SQL docs with SQLAlchemy, ORM mode, relationships
* 🔥 Remove unused util in tutorial
* 📝 Add tutorials for simple dict bodies and responses
* 🔥 Remove old SQL tutorial
* ✅ Add/update tests for SQL tutorial
* ✅ Add tests for simple dicts (body and response)
* 🐛 Fix cloning field from original field
* ✨ Add support for declaring a Response parameter to set headers and cookies
* ✅ Add source for docs and tests
* 📝 Add docs for setting headers, cookies and status code
* 📝 Add attribution to Hug for inspiring response parameters
* ✨ Implement dependency overrides for testing
* ✅ Add docs source tests and extra tests for dependency overrides
* 📝 Add docs for testing dependencies with overrides
* 🐛 Fix path and query parameters accepting dict
* ✅ Add several tests to ensure invalid types are not accepted
* 📝 Document (to include tested source) using query params with list
* 🐛 Fix OpenAPI schema in query with list tutorial
* ✨ Refactor parameter dependency using Pydantic Field
* ⬆️ Upgrade required Pydantic version with latest Shape values
* ✨ Add tutorials and code for using Enum and Optional
* ✅ Add tests for tutorials with new types and extra cases
* ♻️ Format, clean, and add annotations to dependencies.utils
* 📝 Update tutorial for query parameters with list defaults
* ✅ Add tests for query param with list default
* ✨ Make jsonable_encoder's include and exclude receive sequences
* ✨ Add include, exclude, and by_alias to app and router
* ✨ Add and update tutorial code with new parameters
* 📝 Update docs for new parameters and add docs for updating data
* ✅ Add tests for consistency in path operation methods
* ✅ Add tests for new parameters and update tests
* ✨ Upgrade OAuth2 Security with scopes handling
* 📝 Update Security tutorial with OAuth2 and JWT
* ✨ Add tutorial code for OAuth2 with scopes (and JWT)
* ✅ Add tests for tutorial/OAuth2 with scopes
* 🐛 Fix security_scopes type declaration
* ✨ Add docs and tests for SecurityScopes
* ⬆️ Upgrade Pydantic and others (isort), update docs after changes by isort
* 🎨 Format with newest isort, update type hints in jsonable_encoder
* 🔧 Update test script, to avoid Pydantic type errors
* ⬆️ Update pyproject.toml with latest Pydantic
* ✨ Add support for UploadFile annotations
* 📝 Update File upload docs with FileUpload class
* ✅ Add tests for UploadFile support
* 📝 Update UploadFile docs
* 📝 Update Release Notes with issue templates
* ✨ Add HTTPException with support for headers
Including docs and tests
* 📝 Update Security docs to use new HTTPException
✨ SQLAlchemy ORM support
Improved jsonable_encoder with SQLAlchemy support, tests running with SQLite, improved and updated SQL docs
* ➕ Add SQLAlchemy to development dependencies (not required for using FastAPI)
* ➕ Add sqlalchemy to testing dependencies (not required to use FastAPI)
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+.
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).
* **Fast to code**: Increase the speed to develop features by about 200% to 300% *.
* **Less bugs**: Reduce about 40% of human (developer) induced errors. *
* **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%. *
* **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. Less bugs.
* **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" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" 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._"
"_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:
* <a href="https://www.starlette.io/" target="_blank">Starlette</a> for the web parts.
* <a href="https://pydantic-docs.helpmanual.io/" target="_blank">Pydantic</a> for the data parts.
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts.
## Installation
```bash
<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" target="_blank">uvicorn</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>.
<div class="termy">
```console
$ pip install "uvicorn[standard]"
---> 100%
```
</div>
## Example
### Create it
@@ -70,6 +154,8 @@ $ pip install uvicorn
* Create a file `main.py` with:
```Python
fromtypingimportUnion
fromfastapiimportFastAPI
app=FastAPI()
@@ -81,15 +167,18 @@ def read_root():
@app.get("/items/{item_id}")
defread_item(item_id:int,q:str=None):
defread_item(item_id:int,q:Union[str,None]=None):
return{"item_id":item_id,"q":q}
```
<details markdown="1">
<summary>Or use <code>async def</code>...</summary>
If your code uses `async` / `await`, use `async def`:
If you don't know, check the _"In a hurry?"_ section about <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` and `await` in the docs</a>.
</details>
@@ -115,24 +204,34 @@ If you don't know, check the _"In a hurry?"_ section about <a href="https://fast
Run the server with:
```bash
uvicorn main:app --debug
<div class="termy">
```console
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
```
</div>
<details markdown="1">
<summary>About the command <code>uvicorn main:app --debug</code>...</summary>
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
The command `uvicorn main:app` refers to:
* `main`: the file `main.py` (the Python "module").
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
* `--debug`: make the server restart after code changes. Only do this for development.
* `--reload`: make the server restart after code changes. Only do this for development.
</details>
### Check it
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
You will see the JSON response as:
@@ -149,29 +248,29 @@ You already created an API that:
### Interactive API docs
Now go to <a href="http://127.0.0.1:8000/docs" target="_blank">http://127.0.0.1:8000/docs</a>.
Now go to <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 interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" target="_blank">Swagger UI</a>):
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 now, go to <a href="http://127.0.0.1:8000/redoc" target="_blank">http://127.0.0.1:8000/redoc</a>.
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" target="_blank">ReDoc</a>):
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
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`:
@@ -257,7 +354,7 @@ item: Item
* Validation of data:
* Automatic and clear errors when the data is invalid.
* Validation even for deeply nested JSON objects.
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network, to Python data and types. Reading from:
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network to Python data and types. Reading from:
* JSON.
* Path parameters.
* Query parameters.
@@ -286,17 +383,16 @@ 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 is has a required attribute `price` that has to be a `float`.
* 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.
* Convert from and to JSON automatically.
* Document everything as an OpenAPI schema, that can be used by:
* Interactive documentation sytems.
* Document everything with OpenAPI, that can be used by:
* Interactive documentation systems.
* Automatic client code generation systems, for many languages.
* Provide 2 interactive documentation web interfaces directly.
---
We just scratched the surface, but you already get the idea of how it all works.
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/intro/">Tutorial - User Guide</a>.
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
**Spoiler alert**: the tutorial - user guide includes:
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
* How to set **validation constrains** as `maximum_length` or `regex`.
* How to set **validation constraints** as `maximum_length` or `regex`.
* 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.
## Performance
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
## Optional Dependencies
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.
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 `SchemaGenerator` support.
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` 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://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 `pip3 install fastapi[full]`.
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.
If you are using third party libraries that tell you to call them with `await`, like:
```Python
results=awaitsome_library()
```
Then, declare your path operation functions with `async def` like:
```Python hl_lines="2"
@app.get('/')
async def read_results():
results = await some_library()
return results
```
!!! note
You can only use `await` inside of functions created with `async def`.
---
If you are using a third party library that communicates with something (a database, an API, the file system, etc) and doesn't have support for using `await`, (this is currently the case for most database libraries), then declare your path operation functions as normally, with just `def`, like:
```Python hl_lines="2"
@app.get('/')
def results():
results = some_library()
return results
```
---
If your application (somehow) doesn't have to communicate with anything else and wait for it to respond, use `async def`.
---
If you just don't know, use normal `def`.
---
**Note**: you can mix `def` and `async def` in your path operation functions as much as you need and define each one using the best option for you. FastAPI will do the right thing with them.
Anyway, in any of the cases above, FastAPI will still work asynchronously and be extremely fast.
But by following the steps above, it will be able to do some performance optimizations.
## Technical Details
Modern versions of Python have support for **"asynchronous code"** using something called **"coroutines"**, with **`async` and `await`** syntax.
Let's see that phrase by parts in the sections below, below:
* **Asynchronous Code**
* **`async` and `await`**
* **Coroutines**
## Asynchronous Code
Asynchronous code just means that the language has a way to tell the computer / program that at some point in the code, he will have to wait for *something else* to finish somewhere else. Let's say that *something else* is called "slow-file".
So, during that time, the computer can go and do some other work, while "slow-file" finishes.
Then the computer / program will come back every time it has a chance because it's waiting again, or whenever he finished all the work he had at that point. And it will see if any of the tasks he was waiting for has already finished doing whatever it had to do.
And then it takes the first task to finish (let's say, our "slow-file") and continues whatever it had to do with it.
That "wait for something else" normally refers to <abbr title="Input and Output">I/O</abbr> operations that are relatively "slow" (compared to the speed of the processor and the RAM memory), like waiting for:
* the data from the client to be sent through the network
* the data sent by your program to be received by the client through the network
* the contents of a file in the disk to be read by the system and given to your program
* the contents your program gave to the system to be written to disk
* a remote API operation
* a database operation to finish
* a database query to return the results
* etc.
As the execution time is consumed mostly by waiting for <abbr title="Input and Output">I/O</abbr> operations, so they call them "I/O bound".
It's called "asynchronous" because the computer / program doesn't have to be "synchronized" with the slow task, waiting for the exact moment that the task finishes, while doing nothing, to be able to take the task result and continue the work.
Instead of that, by being an "asynchronous" system, once finished, the task can wait in line a little bit (some microseconds) for the computer / program to finish whatever it went to do, and then come back to take the results and continue working with them.
For "synchronous" (contrary to "asynchronous") they commonly also use the term "sequential", because the computer / program follows all the steps in sequence before switching to a different task, even if those steps involve waiting.
### Concurrency and Burgers
This idea of **asynchronous** code described above is also sometimes called **"concurrency"**. It is different from **"parallelism"**.
**Concurrency** and **parallelism** both relate to "different things happening more or less at the same time".
But the details between *concurrency* and *parallelism* are quite different.
To see the difference, imagine the following story about burgers:
### Concurrent Burgers
You go with your crush to get fast food, you stand in line while the cashier takes the orders from the people in front of you.
Then it's your turn, you place your order of 2 very fancy burgers for your crush and you.
You pay.
The cashier says something to the guy in the kitchen so he knows he has to prepare your burgers (even though he is currently preparing the ones for the previous clients).
The cashier gives you the number of your turn.
While you are waiting, you go with your crush and pick a table, you sit and talk with your crush for a long time (as your burgers are very fancy and take some time to prepare).
As you are seating on the table with your crush, while you wait for the burgers, you can spend that time admiring how awesome, cute and smart your crush is.
While waiting and talking to your crush, from time to time, you check the number displayed on the counter to see if it's your turn already.
Then at some point, it finally is your turn. You go to the counter, get your burgers and come back to the table.
You and your crush eat the burgers and have a nice time.
---
Imagine you are the computer / program in that story.
While you are at the line, you are just idle, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier is only taking the orders, so that's fine.
Then, when it's your turn, you do actual "productive" work, you process the menu, decide what you want, get your crush's choice, pay, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc.
But then, even though you still don't have your burgers, your work with the cashier is "on pause", because you have to wait for your burgers to be ready.
But as you go away from the counter and seat on the table with a number for your turn, you can switch your attention to your crush, and "work" on that. Then you are again doing something very "productive", as is flirting with your crush.
Then the cashier says "I'm finished with doing the burgers" by putting your number on the counter display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers because you have the number of your turn, and they have theirs.
So you wait for your crush to finish the story (finish the current work / task being processed), smile gently and say that you are going for the burgers.
Then you go to the counter, to the initial task that is now finished, pick the burgers, say thanks and take them to the table. That finishes that step / task of interaction with the counter. That in turn, creates a new task, of "eating burgers", but the previous one of "getting burgers" is finished.
### Parallel Burgers
You go with your crush to get parallel fast food.
You stand in line while several (let's say 8) cashiers take the orders from the people in front of you.
Everyone before you is waiting for their burgers to be ready before leaving the counter because each of the 8 cashiers goes himself and preparers the burger right away before getting the next order.
Then it's finally your turn, you place your order of 2 very fancy burgers for your crush and you.
You pay.
The cashier goes to the kitchen.
You wait, standing in front of the counter, so that no one else takes your burgers before you, as there are no numbers for turns.
As you and your crush are busy not letting anyone get in front of you and take your burgers whenever they arrive, you cannot pay attention to your crush.
This is "synchronous" work, you are "synchronized" with the cashier/cook. You have to wait and be there at the exact moment that the cashier/cook finishes the burgers and gives them to you, or otherwise, someone else might take them.
Then your cashier/cook finally comes back with your burgers, after a long time waiting there in front of the counter.
You take your burgers and go to the table with your crush.
You just eat them, and you are done.
There was not much talk or flirting as most of the time was spent waiting in front of the counter.
---
In this scenario of the parallel burgers, you are a computer / program with two processors (you and your crush), both waiting and dedicating their attention to be "waiting on the counter" for a long time.
The fast food store has 8 processors (cashiers/cooks). While the concurrent burgers store might have had only 2 (one cashier and one cook).
But still, the final experience is not the best.
---
This would be the parallel equivalent story for burgers.
For a more "real life" example of this, imagine a bank.
Up to recently, most of the banks had multiple cashiers and a big line.
All of the cashiers doing all the work with one client after the other.
And you have to wait in the line for a long time or you lose your turn.
You probably wouldn't want to take your crush with you to do errands at the bank.
### Burger Conclusion
In this scenario of "fast food burgers with your crush", as there is a lot of waiting, it makes a lot more sense to have a concurrent system.
This is the case for most of the web applications.
Many, many users, but your server is waiting for their not-so-good connection to send their requests.
And then waiting again for the responses to come back.
This "waiting" is measured in microseconds, but still, summing it all, it's a lot of waiting in the end.
That's why it makes a lot of sense to use asynchronous code for web APIs.
Most of the existing popular Python frameworks (including Flask and Django) were created before the new asynchronous features in Python existed. So, the ways they can be deployed support parallel execution and an older form of asynchronous execution that is not as powerful as the new capabilities.
Even though the main specification for asynchronous web Python (ASGI) was developed at Django, to add support for WebSockets.
That kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programing language.
And that's the same level of performance</a> you get with **FastAPI**.
And as you can have parallelism and asynchronicity at the same time, you get higher performance than most of the tested NodeJS frameworks and on par with Go, which is a compiled language closer to C <a href="https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1" target="_blank">(all thanks to Starlette)</a>.
### Is concurrency better than parallelism?
Nope! That's not the moral of the story.
Concurrency is different than parallelism. And it is better on **specific** scenarios that involve a lot of waiting. Because of that, it generally is a lot better than parallelism for web application development. But not for everything.
So, to balance that out, imagine the following short story:
> You have to clean a big, dirty house.
*Yep, that's the whole story*.
---
There's no waiting anywhere, just a lot of work to be done, on multiple places of the house.
You could have turns as in the burgers example, first the living room, then the kitchen, but as you are not waiting for anything, just cleaning and cleaning, the turns wouldn't affect anything.
It would take the same amount of time to finish with or without turns (concurrency) and you would have done the same amount of work.
But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
In this scenario, each one of the cleaners (including you) would be a processor, doing their part of the job.
And as most of the execution time is taken by actual work (instead of waiting), and the work in a computer is done by a <abbr title="Central Processing Unit">CPU</abbr>, they call these problems "CPU bound".
---
Common examples of CPU bound operations are things that require complex math processing.
For example:
* **Audio** or **image processing**
* **Computer vision**: an image is composed of millions of pixels, each pixel has 3 values / colors, processing that normally requires computing something on those pixels, all at the same time)
* **Machine Learning**: it normally requires lots of "matrix" and "vector" multiplications. Think of a huge spreadsheet with numbers and multiplying all of them together at the same time.
* **Deep Learning**: this is a sub-field of Machine Learning, so, the same applies. It's just that there is not a single spreadsheet of numbers to multiply, but a huge set of them, and in many cases, you use a special processor to build and / or use those models.
### Concurrency + Parallelism: Web + Machine Learning
With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attractive of NodeJS).
But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems.
That, plus the simple fact that Python is the main language for **Data Science**, Machine Learning and especially Deep Learning, make FastAPI a very good match for Data Science / Machine Learning web APIs and applications (among many others).
To see how to achieve this parallelism in production see the section about [Deployment](deployment.md).
## `async` and `await`
Modern versions of python have a very intuitive way to define asynchronous code. This makes it look just like normal "sequential" code and do the "awaiting" for you at the right moments.
When there is an operation that will require waiting before giving the results and has support for these new Python features, you can code it like:
```Python
burgers = await get_burgers(2)
```
The key here is the `await`. It tells Python that it has to wait for `get_burgers(2)` to finish doing its thing before storing the results in `burgers`. With that, Python will know that it can go and do something else in the meanwhile (like receiving another request).
For `await` to work, it has to be inside a function that supports this asynchronicity. To do that, you just declare it with `async def`:
```Python hl_lines="1"
async def get_burgers(number: int):
# Do some asynchronous stuff to create the burgers
return burgers
```
...instead of `def`:
```Python hl_lines="2"
# This is not asynchronous
def get_sequential_burgers(number: int):
# Do some sequential stuff to create the burgers
return burgers
```
With `async def`, Python knows that, inside that function, it has to be aware of `await` expressions, and that it can "pause" the execution of that function and go do something else before coming back.
When you want to call an `async def` function, you have to "await" it. So, this won't work:
```Python
# This won't work, because get_burgers was defined with: async def
burgers = get_burgers(2)
```
---
So, if you are using a library that tells you that you can call it with `await`, you need to create the path operation functions that uses it with `async def`, like in:
```Python hl_lines="2 3"
@app.get('/burgers')
async def read_burgers():
burgers = await get_burgers(2)
return burgers
```
### More technical details
You might have noticed that `await` can only be used inside of functions defined with `async def`.
But at the same time, functions defined with `async def` have to be "awaited". So, functions with `async def` can only be called inside of functions defined with `async def` too.
So, about the egg and the chicken, how do you call the first `async` function?
If you are working with **FastAPI** you don't have to worry about that, because that "first" function will be your path operation function, and FastAPI will know how to do the right thing.
But if you want to use `async` / `await` without FastAPI, <a href="https://docs.python.org/3/library/asyncio-task.html#coroutine" target="_blank">check the official Python docs</a>
### Other forms of asynchronous code
This style of using `async` and `await` is relatively new in the language.
But it makes working with asynchronous code a lot easier.
This same syntax (or almost identical) was also included recently in modern versions of JavaScript (in Browser and NodeJS).
But before that, handling asynchronous code was quite more complex and difficult.
In previous versions of Python, you could have used threads or <a href="http://www.gevent.org/" target="_blank">Gevent</a>. But the code is way more complex to understand, debug, and think about.
In previous versions of NodeJS / Browser JavaScript, you would have used "callbacks". Which lead to <a href="http://callbackhell.com/" target="_blank">callback hell</a>.
## Coroutines
**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused internally too, whenever there is an `await` inside of it.
But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines".
## Conclusion
Let's see the same phrase from above:
> Modern versions of Python have support for **"asynchronous code"** using something called **"coroutines"**, with **`async` and `await`** syntax.
That should make more sense now.
All that is what powers FastAPI (through Starlette) and what makes it have such an impressive performance.
* <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.
🛠️ 🩺 ⚙️ **🦁 🎚** & **📄**, & 🔠 👈 💪 🕸 & 🎚 📁.
🔢, 👈 📁 🍦 ⚪️➡️ <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>/🧠**:
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - ⏩ 🎻 <abbr title="converting the string that comes from an HTTP request into Python data">"🎻"</abbr>.
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - ✔ 🚥 👆 💚 🐕🦺 📨 <abbr title="converting the string that comes from an HTTP request into Python data">"✍"</abbr>, ⏮️ `request.form()`.
& ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶
#### 💊 🆎
👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼:
=== "🐍 3️⃣.6️⃣ & 🔛"
* `List`
* `Tuple`
* `Set`
* `Dict`
* `Union`
* `Optional`
* ...& 🎏.
=== "🐍 3️⃣.9️⃣ & 🔛"
👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
* `list`
* `tuple`
* `set`
* `dict`
& 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
* `Union`
* `Optional`
* ...& 🎏.
=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
* `list`
* `tuple`
* `set`
* `dict`
& 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
* `Union`
* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
* ...& 🎏.
🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>⏸ ⏸ (`|`)</abbr> 📣 🇪🇺 🆎.
Loaded 100 of 1929 files, more 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.