<ahref="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."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/platform-sh.png"></a>
<ahref="https://www.porter.run"target="_blank"title="Deploy FastAPI on AWS with a few clicks"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/porter.png"></a>
<ahref="https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor"target="_blank"title="Automate FastAPI documentation generation with Bump.sh"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg"></a>
<ahref="https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge"target="_blank"title="Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/scalar.svg"></a>
<ahref="https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge"target="_blank"title="Auth, user management and more for your B2B product"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/propelauth.png"></a>
<ahref="https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral"target="_blank"title="Simplify Full Stack Development with FastAPI & MongoDB"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/mongodb.png"></a>
<ahref="https://zuplo.link/fastapi-gh"target="_blank"title="Zuplo: Scale, Protect, Document, and Monetize your FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a>
<ahref="https://zuplo.link/fastapi-gh"target="_blank"title="Zuplo: Deploy, Secure, Document, and Monetize your FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/zuplo.png"></a>
<ahref="https://liblab.com?utm_source=fastapi"target="_blank"title="liblab - Generate SDKs from FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/liblab.png"></a>
<ahref="https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi"target="_blank"title="Deploy & scale any full-stack web app on Render. Focus on building apps, not infra."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/render.svg"></a>
<ahref="https://www.coderabbit.ai/?utm_source=fastapi&utm_medium=badge&utm_campaign=fastapi"target="_blank"title="Cut Code Review Time & Bugs in Half with CodeRabbit"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/coderabbit.png"></a>
<ahref="https://github.com/deepset-ai/haystack/"target="_blank"title="Build powerful search from composable, open source building blocks"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a>
<ahref="https://databento.com/"target="_blank"title="Pay as you go for market data"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a>
<ahref="https://speakeasy.com?utm_source=fastapi+repo&utm_medium=github+sponsorship"target="_blank"title="SDKs for your API | Speakeasy"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a>
<ahref="https://subtotal.com/?utm_source=fastapi&utm_medium=sponsorship&utm_campaign=open-source"target="_blank"title="The Gold Standard in Retail Account Linking"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/subtotal.svg"></a>
<ahref="https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi"target="_blank"title="Deploy enterprise applications at startup speed"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/railway.png"></a>
<ahref="https://databento.com/?utm_source=fastapi&utm_medium=sponsor&utm_content=display"target="_blank"title="Pay as you go for market data"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/databento.svg"></a>
<ahref="https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship"target="_blank"title="SDKs for your API | Speakeasy"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/speakeasy.png"></a>
<ahref="https://www.svix.com/"target="_blank"title="Svix - Webhooks as a service"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/svix.svg"></a>
<ahref="https://www.permit.io/blog/implement-authorization-in-fastapi?utm_source=github&utm_medium=referral&utm_campaign=fastapi"target="_blank"title="Fine-Grained Authorization for FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/permit.png"></a>
<ahref="https://www.interviewpal.com/?utm_source=fastapi&utm_medium=open-source&utm_campaign=dev-hiring"target="_blank"title="InterviewPal - AI Interview Coach for Engineers and Devs"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/interviewpal.png"></a>
<ahref="https://dribia.com/en/"target="_blank"title="Dribia - Data Science within your reach"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/dribia.png"></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._"
@ -91,7 +89,7 @@ The key features are:
"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
@ -123,14 +121,14 @@ If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
## Requirements
## Requirements { #requirements }
FastAPI stands on the shoulders of giants:
* <ahref="https://www.starlette.io/"class="external-link"target="_blank">Starlette</a> for the web parts.
* <ahref="https://docs.pydantic.dev/"class="external-link"target="_blank">Pydantic</a> for the data parts.
## Installation
## Installation { #installation }
Create and activate a <ahref="https://fastapi.tiangolo.com/virtual-environments/"class="external-link"target="_blank">virtual environment</a> and then install FastAPI:
**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals.
## Example
## Example { #example }
### Create it
### Create it { #create-it }
* Create a file `main.py` with:
Create a file `main.py` with:
```Python
from typing import Union
@ -199,7 +197,7 @@ If you don't know, check the _"In a hurry?"_ section about <a href="https://fast
</details>
### Run it
### Run it { #run-it }
Run the server with:
@ -241,7 +239,7 @@ You can read more about it in the <a href="https://fastapi.tiangolo.com/fastapi-
</details>
### Check it
### Check it { #check-it }
Open your browser at <ahref="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>.
@ -258,7 +256,7 @@ You already created an API that:
* The _path_`/items/{item_id}` has a _path parameter_`item_id` that should be an `int`.
* The _path_`/items/{item_id}` has an optional `str`_query parameter_`q`.
### Interactive API docs
### Interactive API docs { #interactive-api-docs }
Now go to <ahref="http://127.0.0.1:8000/docs"class="external-link"target="_blank">http://127.0.0.1:8000/docs</a>.
@ -266,7 +264,7 @@ You will see the automatic interactive API documentation (provided by <a href="h
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
@ -448,17 +446,17 @@ For a more complete example including more features, see the <a href="https://fa
* **Cookie Sessions**
* ...and more.
## Performance
## Performance { #performance }
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <ahref="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 <ahref="https://fastapi.tiangolo.com/benchmarks/"class="internal-link"target="_blank">Benchmarks</a>.
When you install FastAPI with `pip install "fastapi[standard]"` it comes with the `standard` group of optional dependencies:
@ -472,16 +470,21 @@ Used by Starlette:
* <ahref="https://jinja.palletsprojects.com"target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <ahref="https://github.com/Kludex/python-multipart"target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbrtitle="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
Used by FastAPI / Starlette:
Used by FastAPI:
* <ahref="https://www.uvicorn.org"target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
* `fastapi-cli` - to provide the `fastapi` command.
* `fastapi-cli[standard]` - to provide the `fastapi` command.
* This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to <ahref="https://fastapicloud.com"class="external-link"target="_blank">FastAPI Cloud</a>.
### Without `standard` Dependencies
### Without `standard` Dependencies { #without-standard-dependencies }
If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
### Additional Optional Dependencies
### Without `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
@ -16,7 +16,7 @@ You can learn more about [FastAPI versions and how to pin and upgrade them](http
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.
I (the author, [@tiangolo](https://x.com/tiangolo)) will review it thoroughly and get back to you.
আপনি যদি "এনভায়রনমেন্ট ভেরিয়েবলস" কী এবং সেগুলো কীভাবে ব্যবহার করতে হয় সেটা জানেন, তাহলে এই অংশটি স্কিপ করে যেতে পারেন।
///
এনভায়রনমেন্ট ভেরিয়েবল (সংক্ষেপে "**env var**" নামেও পরিচিত) হলো এমন একটি ভেরিয়েবল যা পাইথন কোডের **বাইরে**, **অপারেটিং সিস্টেমে** থাকে এবং আপনার পাইথন কোড (বা অন্যান্য প্রোগ্রাম) দ্বারা যাকে রিড করা যায়।
এনভায়রনমেন্ট ভেরিয়েবলস অ্যাপ্লিকেশনের **সেটিংস** পরিচালনা করতে, পাইথনের **ইনস্টলেশন** প্রক্রিয়ার অংশ হিসেবে, ইত্যাদি কাজে উপযোগী হতে পারে।
## Env Vars তৈরী এবং ব্যবহার
আপনি **শেল (টার্মিনাল)**-এ, পাইথনের প্রয়োজন ছাড়াই, এনভায়রনমেন্ট ভেরিয়েবলস **তৈরি** এবং ব্যবহার করতে পারবেনঃ
//// tab | লিনাক্স, ম্যাকওএস, উইন্ডোজ Bash
<divclass="termy">
```console
// আপনি চাইলে MY_NAME নামে একটি env var তৈরি করতে পারেন
$ export MY_NAME="Wade Wilson"
// তারপরে এটিকে চাইলে অন্যান্য প্রোগ্রামে ব্যবহার করতে পারেন
$ echo "Hello $MY_NAME"
Hello Wade Wilson
```
</div>
////
//// tab | উইন্ডোজ পাওয়ারশেল
<divclass="termy">
```console
// MY_NAME নামে env var তৈরি
$ $Env:MY_NAME = "Wade Wilson"
// অন্যান্য প্রোগ্রামে এটিকে ব্যবহার
$ echo "Hello $Env:MY_NAME"
Hello Wade Wilson
```
</div>
////
## পাইথনে env vars রিড করা
আপনি চাইলে পাইথনের **বাইরে**, টার্মিনালে (বা অন্য কোনো উপায়ে) এনভায়রনমেন্ট ভেরিয়েবলস তৈরি করতে পারেন, এবং পরে সেগুলো **পাইথনে রিড** (অ্যাক্সেস করতে) পারেন।
উদাহরণস্বরূপ, আপনার `main.py` নামে একটি ফাইল থাকতে পারেঃ
```Python hl_lines="3"
import os
name = os.getenv("MY_NAME", "World")
print(f"Hello {name} from Python")
```
/// tip
<ahref="https://docs.python.org/3.8/library/os.html#os.getenv"class="external-link"target="_blank">`os.getenv()`</a> এর দ্বিতীয় আর্গুমেন্টটি হলো এর ডিফল্ট ভ্যালু যা রিটার্ন করা হবে।
যদি এটি দেওয়া না হয়, ডিফল্টভাবে `None` ব্যবহৃত হবে, এখানে আমরা ডিফল্ট ভ্যালু হিসেবে `"World"` ব্যবহার করেছি।
///
তারপরে পাইথন প্রোগ্রামটিকে নিম্নোক্তভাবে কল করা যাবেঃ
//// tab | লিনাক্স, ম্যাকওএস, উইন্ডোজ Bash
<divclass="termy">
```console
// এখনো আমরা এনভায়রনমেন্ট ভেরিয়েবল সেট করিনি
$ python main.py
// যেহেতু env var সেট করা হয়নি, তাই আমরা ডিফল্ট ভ্যালু পাচ্ছি
Hello World from Python
// কিন্তু আমরা প্রথমে যদি একটা এনভায়রনমেন্ট ভারিয়েবল তৈরি করে নেই
$ export MY_NAME="Wade Wilson"
// এবং তারপর আবার প্রোগ্রাটিকে কল করি
$ python main.py
// এখন এটি এনভায়রনমেন্ট ভেরিয়েবল রিড করতে পারবে
Hello Wade Wilson from Python
```
</div>
////
//// tab | উইন্ডোজ পাওয়ারশেল
<divclass="termy">
```console
// এখনো আমরা এনভায়রনমেন্ট ভেরিয়েবল সেট করিনি
$ python main.py
// যেহেতু env var সেট করা হয়নি, তাই আমরা ডিফল্ট ভ্যালু পাচ্ছি
Hello World from Python
// কিন্তু আমরা প্রথমে যদি একটা এনভায়রনমেন্ট ভারিয়েবল তৈরি করে নেই
$ $Env:MY_NAME = "Wade Wilson"
// এবং তারপর আবার প্রোগ্রাটিকে কল করি
$ python main.py
// এখন এটি এনভায়রনমেন্ট ভেরিয়েবল রিড করতে পারবে
Hello Wade Wilson from Python
```
</div>
////
যেহেতু এনভায়রনমেন্ট ভেরিয়েবলস কোডের বাইরে সেট করা যায়, কিন্তু পরবর্তীতে কোড দ্বারা রিড করা যায়, এবং বাকি ফাইলগুলোর সাথে রাখতে (`git` এ কমিট) হয় না, তাই কনফিগারেশনস বা **সেটিংস** এর জন্য এগুলো সাধারণত ব্যবহৃত হয়ে থাকে।
আপনি একটি এনভায়রনমেন্ট ভেরিয়েবল শুধুমাত্র একটি **নির্দিষ্ট প্রোগ্রাম ইনভোকেশনের** জন্যও তৈরি করতে পারেন, যা শুধুমাত্র সেই প্রোগ্রামের জন্যই এভেইলেবল থাকবে এবং শুধুমাত্র তার চলাকালীন সময় পর্যন্তই সক্রিয় থাকবে।
এটি করতে, প্রোগ্রামটি রান করার ঠিক আগেই, একই লাইনে এনভায়রনমেন্ট ভেরিয়েবল তৈরি করুন:
<divclass="termy">
```console
// প্রোগ্রামটি কল করার সময় একই লাইনে MY_NAME এনভায়রনমেন্ট ভেরিয়েবল তৈরি করুন
$ MY_NAME="Wade Wilson" python main.py
// এখন এটি এনভায়রনমেন্ট ভ্যরিয়েবলটিকে রিড করতে পারবে
Hello Wade Wilson from Python
// পরবর্তীতে এনভায়রনমেন্ট ভেরিয়েবলটিকে আর ব্যবহার করা যাচ্ছে না
$ python main.py
Hello World from Python
```
</div>
/// tip
এটি নিয়ে আরো বিস্তারিত পড়তে পারেন এখানে <ahref="https://12factor.net/config"class="external-link"target="_blank">The Twelve-Factor App: Config</a>।
///
## টাইপস এবং ভ্যালিডেশন
এই এনভায়রনমেন্ট ভেরিয়েবলগুলো শুধুমাত্র **টেক্সট স্ট্রিংস** হ্যান্ডেল করতে পারে, যেহেতু এগুলো পাইথনের বাইরে অবস্থিত এবং অন্যান্য প্রোগ্রাম এবং সিস্টেমের বাকি অংশের (এমনকি বিভিন্ন অপারেটিং সিস্টেম যেমন লিনাক্স, উইন্ডোজ, ম্যাকওএস) সাথে সামঞ্জস্যপূর্ণ হতে হয়।
এর অর্থ হচ্ছে পাইথনে এনভায়রনমেন্ট ভেরিয়েবল থেকে রিড করা **যেকোনো ভ্যালু** একটি `str` হবে, এবং অন্য কোনো টাইপে কনভার্সন বা যেকোনো ভেলিডেশন কোডে আলাদাভাবে করতে হবে।
এনভায়রনমেন্ট ভেরিয়েবল ব্যবহার করে **এপ্লিকেশন সেটিংস** হ্যান্ডেল করা নিয়ে আরো বিস্তারিত জানা যাবে [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}.
## `PATH` এনভায়রনমেন্ট ভেরিয়েবল
**`PATH`** নামে একটি **বিশেষ** এনভায়রনমেন্ট ভেরিয়েবল রয়েছে, যেটি প্রোগ্রাম রান করার জন্য অপারেটিং সিস্টেমস (লিনাক্স, ম্যাকওএস, উইন্ডোজ) দ্বারা ব্যবহৃত হয়।
`PATH` ভেরিয়েবল এর ভ্যালু হচ্ছে একটি বিশাল স্ট্রিং যা ডিরেক্টরিকে কোলন `:` দিয়ে আলাদা করার মাধ্যমে লিনাক্সে ও ম্যাকওএস এ, এবং সেমিকোলন `;` এর মাধ্যমে উইন্ডোজ এ তৈরি করা থাকে।
উদাহরণস্বরূপ, `PATH` ভেরিয়েবল নিচের মতো দেখতে হতে পারেঃ
//// tab | লিনাক্স, ম্যাকওএস
```plaintext
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
```
তারমানে হলো সিস্টেম প্রোগ্রামগুলোকে নিচের ডিরেক্টরিগুলোতে খুঁজবেঃ
তারমানে হলো সিস্টেম প্রোগ্রামগুলোকে নিচের ডিরেক্টরিগুলোতে খুঁজবেঃ
* `C:\Program Files\Python312\Scripts`
* `C:\Program Files\Python312`
* `C:\Windows\System32`
////
যখন আপনি টার্মিনালে কোনো **কমান্ড** লিখবেন, অপারেটিং সিস্টেম **প্রত্যেকটি ডিরেক্টরিতে** প্রোগ্রামটি **খুঁজবে** যেগুলো `PATH` এনভায়রনমেন্ট ভেরিয়েবল এ লিস্ট করা আছে।
উদাহরণস্বরূপ, যখন আপনি টার্মিনালে `python` টাইপ করবেন, অপারেটিং সিস্টেম এই লিস্ট এর **প্রথম ডিরেক্টরিতে**`python` নামের একটি প্রোগ্রাম খুঁজবে।
যদি এটি খুঁজে পায়, তাহলে এটি প্রোগ্রামটিকে ব্যবহার করবে। অন্যথায় এটি **অন্যান্য ডিরেক্টরিগুলোতে** এটিকে খুঁজতে থাকবে।
### পাইথন ইনস্টল এবং `PATH` আপডেট
যখন আপনি পাইথন ইনস্টল করেন, আপনি `PATH` এনভায়রনমেন্ট ভেরিয়েবল আপডেট করতে চান কিনা সেটা জিজ্ঞেস করা হতে পারে।
//// tab | লিনাক্স, ম্যাকওএস
ধরা যাক আপনি পাইথন ইনস্টল করলেন এবং এটি `/opt/custompython/bin` ডিরেক্টরিতে ইনস্টল হচ্ছে।
যদি আপনি "Yes" সিলেক্ট করে `PATH` এনভায়রনমেন্ট ভেরিয়েবল আপডেট করতে চান, তাহলে ইনস্টলার `/opt/custompython/bin` কে `PATH` এনভায়রনমেন্ট ভেরিয়েবল এ এড করে দিবে।
এইভাবে, আপনি যখন টার্মিনালে `python` টাইপ করেন, সিস্টেম পাইথন প্রোগ্রামটিকে `/opt/custompython/bin` (সর্বশেষ ডিরেক্টরি) তে খুঁজে পাবে এবং এটাকে ব্যবহার করবে।
////
//// tab | উইন্ডোজ
ধরা যাক আপনি পাইথন ইনস্টল করলেন এবং এটি `C:\opt\custompython\bin` ডিরেক্টরিতে ইনস্টল হচ্ছে।
যদি আপনি "Yes" সিলেক্ট করে `PATH` এনভায়রনমেন্ট ভেরিয়েবল আপডেট করতে চান, তাহলে ইনস্টলার `C:\opt\custompython\bin` কে `PATH` এনভায়রনমেন্ট ভেরিয়েবল এ এড করে দিবে।
এইভাবে, আপনি যখন টার্মিনালে `python` টাইপ করেন, সিস্টেম পাইথন প্রোগ্রামটিকে `C:\opt\custompython\bin` (সর্বশেষ ডিরেক্টরি) তে খুঁজে পাবে এবং এটাকে ব্যবহার করবে।
////
তাই, আপনি যদি টাইপ করেনঃ
<divclass="termy">
```console
$ python
```
</div>
//// tab | লিনাক্স, ম্যাকওএস
সিস্টেম `python` প্রোগ্রামকে `/opt/custompython/bin` এ **খুঁজে পাবে** এবং এটাকে রান করবে।
এটা মোটামুটিভাবে নিচের মতো করে লেখার সমান হবেঃ
<divclass="termy">
```console
$ /opt/custompython/bin/python
```
</div>
////
//// tab | উইন্ডোজ
সিস্টেম `python` প্রোগ্রামকে `C:\opt\custompython\bin\python` এ **খুঁজে পাবে** এবং এটাকে রান করবে।
এটা মোটামুটিভাবে নিচের মতো করে লেখার সমান হবেঃ
<divclass="termy">
```console
$ C:\opt\custompython\bin\python
```
</div>
////
এই তথ্যগুলো [ভার্চুয়াল এনভায়রনমেন্টস](virtual-environments.md){.internal-link target=_blank} শেখার ক্ষেত্রে সহায়ক হবে।
## উপসংহার
এর মাধ্যমে আপনি **এনভায়রনমেন্ট ভেরিয়েবলস** কি এবং এটিকে পাইথনে কিভাবে ব্যবহার করতে হয় তার সম্পর্কে বেসিক ধারনা পেলেন।
চাইলে এই সম্পর্কে আরো বিস্তারিত পড়তে পারেন <ahref="https://en.wikipedia.org/wiki/Environment_variable"class="external-link"target="_blank">Wikipedia for Environment Variable</a> এ।
অনেক ক্ষেত্রে, দেখা মাত্রই এনভায়রনমেন্ট ভেরিয়েবল কীভাবে প্রয়োজন হবে তা স্পষ্ট হয় না। কিন্তু ডেভেলপমেন্টের সময় আপনি নানা রকম পরিস্থিতিতে এগুলোর সম্মুখীন হবেন, তাই এগুলো সম্পর্কে জেনে রাখা ভালো।
উদাহরণস্বরূপ, আপনার এই ইনফরমেশনটি পরবর্তী, [ভার্চুয়াল এনভায়রনমেন্টস](virtual-environments.md) অংশে দরকার হবে।
@ -20,7 +20,7 @@ Einige von diesen ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponse
Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇
Beispielsweise könnten Sie <ahref="https://speakeasy.com/?utm_source=fastapi+repo&utm_medium=github+sponsorship"class="external-link"target="_blank">Speakeasy</a> ausprobieren.
Beispielsweise könnten Sie <ahref="https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship"class="external-link"target="_blank">Speakeasy</a> ausprobieren.
Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und die Sie online suchen und finden können. 🤓
@ -4,9 +4,9 @@ Sie können OAuth2-<abbr title="Geltungsbereiche">Scopes</abbr> direkt in **Fast
Das ermöglicht es Ihnen, ein feingranuliertes Berechtigungssystem nach dem OAuth2-Standard in Ihre OpenAPI-Anwendung (und deren API-Dokumentation) zu integrieren.
OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, Twitter usw. verwendet wird. Sie verwenden ihn, um Benutzern und Anwendungen spezifische Berechtigungen zu erteilen.
OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, X (Twitter) usw. verwendet wird. Sie verwenden ihn, um Benutzern und Anwendungen spezifische Berechtigungen zu erteilen.
Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter anmelden („log in with“), verwendet die entsprechende Anwendung OAuth2 mit Scopes.
Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder X (Twitter) anmelden („log in with“), verwendet die entsprechende Anwendung OAuth2 mit Scopes.
In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten.
@ -381,7 +381,7 @@ Davor war der Umgang mit asynchronem Code jedoch deutlich komplexer und schwieri
In früheren Versionen von Python hätten Sie Threads oder <ahref="https://www.gevent.org/"class="external-link"target="_blank">Gevent</a> verwenden können. Der Code ist jedoch viel komplexer zu verstehen, zu debuggen und nachzuvollziehen.
In früheren Versionen von NodeJS / Browser JavaScript hätten Sie „Callbacks“ verwendet. Was zur <ahref="http://callbackhell.com/"class="external-link"target="_blank">Callback-Hölle</a> führt.
In früheren Versionen von NodeJS / Browser JavaScript hätten Sie „Callbacks“ verwendet. Was zur "Callback-Hölle" führt.
@ -10,8 +10,4 @@ Einige Cloud-Anbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sp
Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇
Vielleicht möchten Sie deren Dienste ausprobieren und deren Anleitungen folgen:
@ -216,7 +216,7 @@ Dieser Manager-Prozess wäre wahrscheinlich derjenige, welcher der IP am **Port*
Diese Workerprozesse würden Ihre Anwendung ausführen, sie würden die Hauptberechnungen durchführen, um einen **Request** entgegenzunehmen und eine **Response** zurückzugeben, und sie würden alles, was Sie in Variablen einfügen, in den RAM laden.
@ -85,7 +85,7 @@ Zuerst würde der Browser mithilfe der **DNS-Server** herausfinden, welches die
Die DNS-Server geben dem Browser eine bestimmte **IP-Adresse** zurück. Das wäre die von Ihrem Server verwendete öffentliche IP-Adresse, die Sie in den DNS-Servern konfiguriert haben.
@ -93,7 +93,7 @@ Der Browser kommuniziert dann mit dieser IP-Adresse über **Port 443** (den HTTP
Der erste Teil der Kommunikation besteht lediglich darin, die Verbindung zwischen dem Client und dem Server herzustellen und die zu verwendenden kryptografischen Schlüssel usw. zu vereinbaren.
Diese Interaktion zwischen dem Client und dem Server zum Aufbau der TLS-Verbindung wird als **<abbrtitle="TLS-Handschlag">TLS-Handshake</abbr>** bezeichnet.
@ -111,7 +111,7 @@ Mithilfe der oben beschriebenen **SNI-Erweiterung** würde der TLS-Terminierungs
In diesem Fall würde er das Zertifikat für `someapp.example.com` verwenden.
Der Client **vertraut** bereits der Entität, die das TLS-Zertifikat generiert hat (in diesem Fall Let's Encrypt, aber wir werden später mehr darüber erfahren), sodass er **verifizieren** kann, dass das Zertifikat gültig ist.
@ -133,19 +133,19 @@ Da Client und Server (sprich, der Browser und der TLS-Terminierungsproxy) nun ü
Der Client sendet also einen **HTTPS-Request**. Das ist einfach ein HTTP-Request über eine verschlüsselte TLS-Verbindung.
Der TLS-Terminierungsproxy würde die vereinbarte Verschlüsselung zum **Entschlüsseln des Requests** verwenden und den **einfachen (entschlüsselten) HTTP-Request** an den Prozess weiterleiten, der die Anwendung ausführt (z. B. einen Prozess, bei dem Uvicorn die FastAPI-Anwendung ausführt).
@ -153,7 +153,7 @@ Der TLS-Terminierungsproxy würde dann die Response mithilfe der zuvor vereinbar
Als Nächstes überprüft der Browser, ob die Response gültig und mit dem richtigen kryptografischen Schlüssel usw. verschlüsselt ist. Anschließend **entschlüsselt er die Response** und verarbeitet sie.
Der Client (Browser) weiß, dass die Response vom richtigen Server kommt, da dieser die Kryptografie verwendet, die zuvor mit dem **HTTPS-Zertifikat** vereinbart wurde.
@ -163,7 +163,7 @@ Auf demselben Server (oder denselben Servern) könnten sich **mehrere Anwendunge
Nur ein Prozess kann diese spezifische IP und den Port verarbeiten (in unserem Beispiel der TLS-Terminierungsproxy), aber die anderen Anwendungen/Prozesse können auch auf dem/den Server(n) ausgeführt werden, solange sie nicht versuchen, dieselbe **Kombination aus öffentlicher IP und Port** zu verwenden.
Auf diese Weise könnte der TLS-Terminierungsproxy HTTPS und Zertifikate für **mehrere Domains**, für mehrere Anwendungen, verarbeiten und die Requests dann jeweils an die richtige Anwendung weiterleiten.
@ -173,7 +173,7 @@ Irgendwann in der Zukunft würde jedes Zertifikat **ablaufen** (etwa 3 Monate na
Und dann gäbe es ein anderes Programm (in manchen Fällen ist es ein anderes Programm, in manchen Fällen ist es derselbe TLS-Terminierungsproxy), das mit Let's Encrypt kommuniziert und das/die Zertifikat(e) erneuert.
<imgsrc="/img/deployment/https/https.svg">
<imgsrc="/img/deployment/https/https.drawio.svg">
Die **TLS-Zertifikate** sind **einem Domainnamen zugeordnet**, nicht einer IP-Adresse.
@ -19,9 +19,9 @@ Sie können den (unregelmäßig erscheinenden) [**FastAPI and Friends**-Newslett
* Funktionen ✨
* Breaking Changes 🚨
* Tipps und Tricks ✅
## FastAPI auf Twitter folgen
## FastAPI auf X (Twitter) folgen
<ahref="https://twitter.com/fastapi"class="external-link"target="_blank">Folgen Sie @fastapi auf **Twitter**</a>, um die neuesten Nachrichten über **FastAPI** zu erhalten. 🐦
<ahref="https://x.com/fastapi"class="external-link"target="_blank">Folgen Sie @fastapi auf **X (Twitter)**</a>, um die neuesten Nachrichten über **FastAPI** zu erhalten. 🐦
## **FastAPI** auf GitHub einen Stern geben
@ -46,19 +46,19 @@ Insbesondere:
* <ahref="https://github.com/tiangolo"class="external-link"target="_blank"> Folgen Sie mir auf **GitHub**</a>.
* Finden Sie andere Open-Source-Projekte, die ich erstellt habe und die Ihnen helfen könnten.
* Folgen Sie mir, um mitzubekommen, wenn ich ein neues Open-Source-Projekt erstelle.
* <ahref="https://twitter.com/tiangolo"class="external-link"target="_blank">Folgen Sie mir auf **Twitter**</a> oder <ahref="https://fosstodon.org/@tiangolo"class="external-link"target="_blank">Mastodon</a>.
* <ahref="https://x.com/tiangolo"class="external-link"target="_blank">Folgen Sie mir auf **X (Twitter)**</a> oder <ahref="https://fosstodon.org/@tiangolo"class="external-link"target="_blank">Mastodon</a>.
* Berichten Sie mir, wie Sie FastAPI verwenden (das höre ich gerne).
* Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche.
* Sie können auch <ahref="https://twitter.com/fastapi"class="external-link"target="_blank">@fastapi auf Twitter folgen</a> (ein separates Konto).
* Sie können auch <ahref="https://x.com/fastapi"class="external-link"target="_blank">@fastapi auf X (Twitter) folgen</a> (ein separates Konto).
* <ahref="https://www.linkedin.com/in/tiangolo/"class="external-link"target="_blank">Folgen Sie mir auf **LinkedIn**</a>.
* Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche (obwohl ich Twitter häufiger verwende 🤷♂).
* Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche (obwohl ich X (Twitter) häufiger verwende 🤷♂).
* Lesen Sie, was ich schreibe (oder folgen Sie mir) auf <ahref="https://dev.to/tiangolo"class="external-link"target="_blank">**Dev.to**</a> oder <ahref="https://medium.com/@tiangolo"class="external-link"target="_blank">**Medium**</a>.
* Lesen Sie andere Ideen, Artikel, und erfahren Sie mehr über die von mir erstellten Tools.
* Folgen Sie mir, um zu lesen, wenn ich etwas Neues veröffentliche.
## Über **FastAPI** tweeten
<ahref="https://twitter.com/compose/tweet?text=Ich liebe @fastapi, weil ... https://github.com/fastapi/fastapi"class="external-link"target="_blank">Tweeten Sie über **FastAPI**</a> und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉
<ahref="https://x.com/compose/tweet?text=Ich liebe @fastapi, weil ... https://github.com/fastapi/fastapi"class="external-link"target="_blank">Tweeten Sie über **FastAPI**</a> und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉
Ich höre gerne, wie **FastAPI** verwendet wird, was Ihnen daran gefallen hat, in welchem Projekt/Unternehmen Sie es verwenden, usw.
* Es gibt auch ein Unterverzeichnis `app/internal/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein weiteres „Python-Subpackage“: `app.internal`.
* Und die Datei `app/internal/admin.py` ist ein weiteres Submodul: `app.internal.admin`.
@ -22,7 +22,7 @@ Es handelt sich um eine recht umfangreiche Spezifikation, und sie deckt mehrere
Sie umfasst Möglichkeiten zur Authentifizierung mithilfe eines „Dritten“ („third party“).
Das ist es, was alle diese „Login mit Facebook, Google, Twitter, GitHub“-Systeme unter der Haube verwenden.
Das ist es, was alle diese „Login mit Facebook, Google, X (Twitter), GitHub“-Systeme unter der Haube verwenden.
### OAuth 1
@ -79,7 +79,7 @@ OpenAPI definiert die folgenden Sicherheitsschemas:
* HTTP Basic Authentication.
* HTTP Digest, usw.
* `oauth2`: Alle OAuth2-Methoden zum Umgang mit Sicherheit (genannt „Flows“).
* Mehrere dieser Flows eignen sich zum Aufbau eines OAuth 2.0-Authentifizierungsanbieters (wie Google, Facebook, Twitter, GitHub usw.):
* Mehrere dieser Flows eignen sich zum Aufbau eines OAuth 2.0-Authentifizierungsanbieters (wie Google, Facebook, X (Twitter), GitHub usw.):
* `implicit`
* `clientCredentials`
* `authorizationCode`
@ -91,7 +91,7 @@ OpenAPI definiert die folgenden Sicherheitsschemas:
/// tip | Tipp
Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach.
Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, X (Twitter), GitHub, usw. ist möglich und relativ einfach.
Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird.
@ -272,4 +272,4 @@ Aber es bietet Ihnen die Werkzeuge, um den Prozess so weit wie möglich zu verei
Und Sie können sichere Standardprotokolle wie OAuth2 auf relativ einfache Weise verwenden und implementieren.
Im **Handbuch für fortgeschrittene Benutzer** erfahren Sie mehr darüber, wie Sie OAuth2-„Scopes“ für ein feingranuliertes Berechtigungssystem verwenden, das denselben Standards folgt. OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, Twitter, usw. verwendet wird, um Drittanbieteranwendungen zu autorisieren, im Namen ihrer Benutzer mit ihren APIs zu interagieren.
Im **Handbuch für fortgeschrittene Benutzer** erfahren Sie mehr darüber, wie Sie OAuth2-„Scopes“ für ein feingranuliertes Berechtigungssystem verwenden, das denselben Standards folgt. OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, X (Twitter), usw. verwendet wird, um Drittanbieteranwendungen zu autorisieren, im Namen ihrer Benutzer mit ihren APIs zu interagieren.
## Combine predefined responses and custom ones { #combine-predefined-responses-and-custom-ones }
You might want to have some predefined responses that apply to many *path operations*, but you want to combine them with custom responses needed by each *path operation*.
# Additional Status Codes { #additional-status-codes }
By default, **FastAPI** will return the responses using a `JSONResponse`, putting the content you return from your *path operation* inside of that `JSONResponse`.
It will use the default status code or the one you set in your *path operation*.
## Additional status codes
## Additional status codes { #additional-status-codes_1 }
If you want to return additional status codes apart from the main one, you can do that by returning a `Response` directly, like a `JSONResponse`, and set the additional status code directly.
@ -34,7 +34,7 @@ You could also use `from starlette.responses import JSONResponse`.
///
## OpenAPI and API docs
## OpenAPI and API docs { #openapi-and-api-docs }
If you return additional status codes and responses directly, they won't be included in the OpenAPI schema (the API docs), because FastAPI doesn't have a way to know beforehand what you are going to return.
All the dependencies we have seen are a fixed function or class.
@ -10,7 +10,7 @@ Let's imagine that we want to have a dependency that checks if the query paramet
But we want to be able to parameterize that fixed content.
## A "callable" instance
## A "callable" instance { #a-callable-instance }
In Python there's a way to make an instance of a class a "callable".
@ -22,7 +22,7 @@ To do that, we declare a method `__call__`:
In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later.
## Parameterize the instance
## Parameterize the instance { #parameterize-the-instance }
And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency:
@ -30,7 +30,7 @@ And now, we can use `__init__` to declare the parameters of the instance that we
In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code.
## Create an instance
## Create an instance { #create-an-instance }
We could create an instance of this class with:
@ -38,7 +38,7 @@ We could create an instance of this class with:
And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`.
## Use the instance as a dependency
## Use the instance as a dependency { #use-the-instance-as-a-dependency }
Then, we could use this `checker` in a `Depends(checker)`, instead of `Depends(FixedContentQueryChecker)`, because the dependency is the instance, `checker`, not the class itself.
You have already seen how to test your **FastAPI** applications using the provided `TestClient`. Up to now, you have only seen how to write synchronous tests, without using `async` functions.
@ -6,11 +6,11 @@ Being able to use asynchronous functions in your tests could be useful, for exam
Let's look at how we can make that work.
## pytest.mark.anyio
## pytest.mark.anyio { #pytest-mark-anyio }
If we want to call asynchronous functions in our tests, our test functions have to be asynchronous. AnyIO provides a neat plugin for this, that allows us to specify that some test functions are to be called asynchronously.
## HTTPX
## HTTPX { #httpx }
Even if your **FastAPI** application uses normal `def` functions instead of `async def`, it is still an `async` application underneath.
@ -18,7 +18,7 @@ The `TestClient` does some magic inside to call the asynchronous FastAPI applica
The `TestClient` is based on <ahref="https://www.python-httpx.org"class="external-link"target="_blank">HTTPX</a>, and luckily, we can use it directly to test the API.
## Example
## Example { #example }
For a simple example, let's consider a file structure similar to the one described in [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} and [Testing](../tutorial/testing.md){.internal-link target=_blank}:
@ -38,7 +38,7 @@ The file `test_main.py` would have the tests for `main.py`, it could look like t
{* ../../docs_src/async_tests/test_main.py *}
## Run it
## Run it { #run-it }
You can run your tests as usual via:
@ -52,7 +52,7 @@ $ pytest
</div>
## In Detail
## In Detail { #in-detail }
The marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously:
@ -88,7 +88,7 @@ If your application relies on lifespan events, the `AsyncClient` won't trigger t
///
## Other Asynchronous Function Calls
## Other Asynchronous Function Calls { #other-asynchronous-function-calls }
As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code.
In some situations, you might need to use a **proxy** server like Traefik or Nginx with a configuration that adds an extra path prefix that is not seen by your application.
In many situations, you would use a **proxy** like Traefik or Nginx in front of your FastAPI app.
These proxies could handle HTTPS certificates and other things.
A **proxy** in front of your application would normally set some headers on the fly before sending the requests to your **server** to let the server know that the request was **forwarded** by the proxy, letting it know the original (public) URL, including the domain, that it is using HTTPS, etc.
The **server** program (for example **Uvicorn** via **FastAPI CLI**) is capable of interpreting these headers, and then passing that information to your application.
But for security, as the server doesn't know it is behind a trusted proxy, it won't interpret those headers.
You can start FastAPI CLI with the *CLI Option*`--forwarded-allow-ips` and pass the IP addresses that should be trusted to read those forwarded headers.
If you set it to `--forwarded-allow-ips="*"` it would trust all the incoming IPs.
If your **server** is behind a trusted **proxy** and only the proxy talks to it, this would make it accept whatever is the IP of that **proxy**.
<divclass="termy">
```console
$ fastapi run --forwarded-allow-ips="*"
<spanstyle="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
### Redirects with HTTPS { #redirects-with-https }
For example, let's say you define a *path operation*`/items/`:
The **proxy** intercepts the original client request and adds the special *forwarded* headers (`X-Forwarded-*`) before passing the request to the **application server**.
These headers preserve information about the original request that would otherwise be lost:
* **X-Forwarded-For**: The original client's IP address
* **X-Forwarded-Proto**: The original protocol (`https`)
* **X-Forwarded-Host**: The original host (`mysuperapp.com`)
When **FastAPI CLI** is configured with `--forwarded-allow-ips`, it trusts these headers and uses them, for example to generate the correct URLs in redirects.
## Proxy with a stripped path prefix { #proxy-with-a-stripped-path-prefix }
You could have a proxy that adds a path prefix to your application.
In these cases you can use `root_path` to configure your application.
@ -10,8 +109,6 @@ The `root_path` is used to handle these specific cases.
And it's also used internally when mounting sub-applications.
## Proxy with a stripped path prefix
Having a proxy with a stripped path prefix, in this case, means that you could declare a path at `/app` in your code, but then, you add a layer on top (the proxy) that would put your **FastAPI** application under a path like `/api/v1`.
In this case, the original path `/app` would actually be served at `/api/v1/app`.
@ -66,14 +163,14 @@ The docs UI would also need the OpenAPI schema to declare that this API `server`
In this example, the "Proxy" could be something like **Traefik**. And the server would be something like FastAPI CLI with **Uvicorn**, running your FastAPI application.
### Providing the `root_path`
### Providing the `root_path` { #providing-the-root-path }
To achieve this, you can use the command line option `--root-path` like:
<divclass="termy">
```console
$ fastapi run main.py --root-path /api/v1
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<spanstyle="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@ -90,7 +187,7 @@ And the `--root-path` command line option provides that `root_path`.
///
### Checking the current `root_path`
### Checking the current `root_path` { #checking-the-current-root-path }
You can get the current `root_path` used by your application for each request, it is part of the `scope` dictionary (that's part of the ASGI spec).
@ -103,7 +200,7 @@ Then, if you start Uvicorn with:
<divclass="termy">
```console
$ fastapi run main.py --root-path /api/v1
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<spanstyle="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
@ -119,7 +216,7 @@ The response would be something like:
}
```
### Setting the `root_path` in the FastAPI app
### Setting the `root_path` in the FastAPI app { #setting-the-root-path-in-the-fastapi-app }
Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app:
@ -127,7 +224,7 @@ Alternatively, if you don't have a way to provide a command line option like `--
Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn.
### About `root_path`
### About `root_path` { #about-root-path }
Keep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app.
@ -144,7 +241,7 @@ So, it won't expect to be accessed at `http://127.0.0.1:8000/api/v1/app`.
Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`, and then it would be the proxy's responsibility to add the extra `/api/v1` prefix on top.
## About proxies with a stripped path prefix
## About proxies with a stripped path prefix { #about-proxies-with-a-stripped-path-prefix }
Keep in mind that a proxy with stripped path prefix is only one of the ways to configure it.
@ -152,7 +249,7 @@ Probably in many cases the default will be that the proxy doesn't have a strippe
In a case like that (without a stripped path prefix), the proxy would listen on something like `https://myawesomeapp.com`, and then if the browser goes to `https://myawesomeapp.com/api/v1/app` and your server (e.g. Uvicorn) listens on `http://127.0.0.1:8000` the proxy (without a stripped path prefix) would access Uvicorn at the same path: `http://127.0.0.1:8000/api/v1/app`.
## Testing locally with Traefik
## Testing locally with Traefik { #testing-locally-with-traefik }
You can easily run the experiment locally with a stripped path prefix using <ahref="https://docs.traefik.io/"class="external-link"target="_blank">Traefik</a>.
@ -224,14 +321,14 @@ And now start your app, using the `--root-path` option:
<divclass="termy">
```console
$ fastapi run main.py --root-path /api/v1
$ fastapi run main.py --forwarded-allow-ips="*" --root-path /api/v1
<spanstyle="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
</div>
### Check the responses
### Check the responses { #check-the-responses }
Now, if you go to the URL with the port for Uvicorn: <ahref="http://127.0.0.1:8000/app"class="external-link"target="_blank">http://127.0.0.1:8000/app</a>, you will see the normal response:
@ -267,7 +364,7 @@ And the version without the path prefix (`http://127.0.0.1:8000/app`), provided
That demonstrates how the Proxy (Traefik) uses the path prefix and how the server (Uvicorn) uses the `root_path` from the option `--root-path`.
### Check the docs UI
### Check the docs UI { #check-the-docs-ui }
But here's the fun part. ✨
@ -287,7 +384,7 @@ Right as we wanted it. ✔️
This is because FastAPI uses this `root_path` to create the default `server` in OpenAPI with the URL provided by `root_path`.
## Additional servers
## Additional servers { #additional-servers }
/// warning
@ -346,7 +443,7 @@ The docs UI will interact with the server that you select.
///
### Disable automatic server from `root_path`
### Disable automatic server from `root_path` { #disable-automatic-server-from-root-path }
If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`:
@ -354,7 +451,7 @@ If you don't want **FastAPI** to include an automatic server using the `root_pat
and then it won't include it in the OpenAPI schema.
## Mounting a sub-application
## Mounting a sub-application { #mounting-a-sub-application }
If you need to mount a sub-application (as described in [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect.
By default, **FastAPI** will return the responses using `JSONResponse`.
@ -18,7 +18,7 @@ If you use a response class with no media type, FastAPI will expect your respons
///
## Use `ORJSONResponse`
## Use `ORJSONResponse` { #use-orjsonresponse }
For example, if you are squeezing performance, you can install and use <ahref="https://github.com/ijl/orjson"class="external-link"target="_blank">`orjson`</a> and set the response to be `ORJSONResponse`.
@ -48,7 +48,7 @@ The `ORJSONResponse` is only available in FastAPI, not in Starlette.
///
## HTML Response
## HTML Response { #html-response }
To return a response with HTML directly from **FastAPI**, use `HTMLResponse`.
@ -67,7 +67,7 @@ And it will be documented as such in OpenAPI.
///
### Return a `Response`
### Return a `Response` { #return-a-response }
As seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}, you can also override the response directly in your *path operation*, by returning it.
@ -87,13 +87,13 @@ Of course, the actual `Content-Type` header, status code, etc, will come from th
///
### Document in OpenAPI and override `Response`
### Document in OpenAPI and override `Response` { #document-in-openapi-and-override-response }
If you want to override the response from inside of the function but at the same time document the "media type" in OpenAPI, you can use the `response_class` parameter AND return a `Response` object.
The `response_class` will then be used only to document the OpenAPI *path operation*, but your `Response` will be used as is.
#### Return an `HTMLResponse` directly
#### Return an `HTMLResponse` directly { #return-an-htmlresponse-directly }
For example, it could be something like:
@ -107,7 +107,7 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi
You can also declare the media type and many other details in OpenAPI using `responses`: [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
FastAPI is built on top of **Pydantic**, and I have been showing you how to use Pydantic models to declare requests and responses.
@ -28,7 +28,7 @@ But if you have a bunch of dataclasses laying around, this is a nice trick to us
///
## Dataclasses in `response_model`
## Dataclasses in `response_model` { #dataclasses-in-response-model }
You can also use `dataclasses` in the `response_model` parameter:
@ -40,7 +40,7 @@ This way, its schema will show up in the API docs user interface:
<imgsrc="/img/tutorial/dataclasses/image01.png">
## Dataclasses in Nested Data Structures
## Dataclasses in Nested Data Structures { #dataclasses-in-nested-data-structures }
You can also combine `dataclasses` with other type annotations to make nested data structures.
@ -84,12 +84,12 @@ You can combine `dataclasses` with other type annotations in many different comb
Check the in-code annotation tips above to see more specific details.
## Learn More
## Learn More { #learn-more }
You can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc.
To learn more, check the <ahref="https://docs.pydantic.dev/latest/concepts/dataclasses/"class="external-link"target="_blank">Pydantic docs about dataclasses</a>.
## Version
## Version { #version }
This is available since FastAPI version `0.67.0`. 🔖
You can define logic (code) that should be executed before the application **starts up**. This means that this code will be executed **once**, **before** the application **starts receiving requests**.
@ -8,7 +8,7 @@ Because this code is executed before the application **starts** taking requests,
This can be very useful for setting up **resources** that you need to use for the whole app, and that are **shared** among requests, and/or that you need to **clean up** afterwards. For example, a database connection pool, or loading a shared machine learning model.
## Use Case
## Use Case { #use-case }
Let's start with an example **use case** and then see how to solve it with this.
@ -22,7 +22,7 @@ You could load it at the top level of the module/file, but that would also mean
That's what we'll solve, let's load the model before the requests are handled, but only right before the application starts receiving requests, not while the code is being loaded.
## Lifespan
## Lifespan { #lifespan }
You can define this *startup* and *shutdown* logic using the `lifespan` parameter of the `FastAPI` app, and a "context manager" (I'll show you what that is in a second).
@ -44,7 +44,7 @@ Maybe you need to start a new version, or you just got tired of running it. 🤷
///
### Lifespan function
### Lifespan function { #lifespan-function }
The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`.
@ -54,7 +54,7 @@ The first part of the function, before the `yield`, will be executed **before**
And the part after the `yield` will be executed **after** the application has finished.
If you check, the function is decorated with an `@asynccontextmanager`.
@ -84,7 +84,7 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager**
{* ../../docs_src/events/tutorial003.py hl[22] *}
## Alternative Events (deprecated)
## Alternative Events (deprecated) { #alternative-events-deprecated }
/// warning
@ -100,7 +100,7 @@ You can define event handlers (functions) that need to be executed before the ap
These functions can be declared with `async def` or normal `def`.
### `startup` event
### `startup` event { #startup-event }
To add a function that should be run before the application starts, declare it with the event `"startup"`:
@ -112,7 +112,7 @@ You can add more than one event handler function.
And your application won't start receiving requests until all the `startup` event handlers have completed.
### `shutdown` event
### `shutdown` event { #shutdown-event }
To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`:
@ -138,7 +138,7 @@ So, we declare the event handler function with standard `def` instead of `async
///
### `startup` and `shutdown` together
### `startup` and `shutdown` together { #startup-and-shutdown-together }
There's a high chance that the logic for your *startup* and *shutdown* is connected, you might want to start something and then finish it, acquire a resource and then release it, etc.
@ -146,7 +146,7 @@ Doing that in separated functions that don't share logic or variables together i
Because of that, it's now recommended to instead use the `lifespan` as explained above.
## Technical Details
## Technical Details { #technical-details }
Just a technical detail for the curious nerds. 🤓
@ -160,6 +160,6 @@ Including how to handle lifespan state that can be used in other areas of your c
///
## Sub Applications
## Sub Applications { #sub-applications }
🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}.
As **FastAPI** is based on the OpenAPI specification, you get automatic compatibility with many tools, including the automatic API docs (provided by Swagger UI).
Because **FastAPI** is based on the **OpenAPI** specification, its APIs can be described in a standard format that many tools understand.
One particular advantage that is not necessarily obvious is that you can **generate clients** (sometimes called <abbrtitle="Software Development Kits">**SDKs**</abbr> ) for your API, for many different **programming languages**.
This makes it easy to generate up-to-date **documentation**, client libraries (<abbrtitle="Software Development Kits">**SDKs**</abbr>) in multiple languages, and **testing** or **automation workflows** that stay in sync with your code.
## OpenAPI Client Generators
In this guide, you'll learn how to generate a **TypeScript SDK** for your FastAPI backend.
There are many tools to generate clients from **OpenAPI**.
## Open Source SDK Generators { #open-source-sdk-generators }
A common tool is<ahref="https://openapi-generator.tech/"class="external-link"target="_blank">OpenAPI Generator</a>.
A versatile option is the<ahref="https://openapi-generator.tech/"class="external-link"target="_blank">OpenAPI Generator</a>, which supports **many programming languages** and can generate SDKs from your OpenAPI specification.
If you are building a **frontend**, a very interesting alternative is<ahref="https://github.com/hey-api/openapi-ts"class="external-link"target="_blank">openapi-ts</a>.
For **TypeScript clients**,<ahref="https://heyapi.dev/"class="external-link"target="_blank">Hey API</a> is a purpose-built solution, providing an optimized experience for the TypeScript ecosystem.
## Client and SDK Generators - Sponsor
You can discover more SDK generators on <ahref="https://openapi.tools/#sdk"class="external-link"target="_blank">OpenAPI.Tools</a>.
There are also some **company-backed** Client and SDK generators based on OpenAPI (FastAPI), in some cases they can offer you **additional features** on top of high-quality generated SDKs/clients.
/// tip
FastAPI automatically generates **OpenAPI 3.1** specifications, so any tool you use must support this version.
///
## SDK Generators from FastAPI Sponsors { #sdk-generators-from-fastapi-sponsors }
This section highlights **venture-backed** and **company-supported** solutions from companies that sponsor FastAPI. These products provide **additional features** and **integrations** on top of high-quality generated SDKs.
Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**.
By ✨ [**sponsoring FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, these companies help ensure the framework and its **ecosystem** remain healthy and **sustainable**.
And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇
Their sponsorship also demonstrates a strong commitment to the FastAPI **community** (you), showing that they care not only about offering a **great service** but also about supporting a **robust and thriving framework**, FastAPI. 🙇
There are also several other companies offering similar services that you can search and find online. 🤓
Some of these solutions may also be open source or offer free tiers, so you can try them without a financial commitment. Other commercial SDK generators are available and can be found online. 🤓
## Generate a TypeScript Frontend Client
## Create a TypeScript SDK { #create-a-typescript-sdk }
Let's start with a simple FastAPI application:
@ -36,80 +44,33 @@ Let's start with a simple FastAPI application:
Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`.
### API Docs
### API Docs { #api-docs }
If you go to the API docs, you will see that it has the **schemas** for the data to be sent in requests and received in responses:
If you go to `/docs`, you will see that it has the **schemas** for the data to be sent in requests and received in responses:
You can see those schemas because they were declared with the models in the app.
That information is available in the app's **OpenAPI schema**, and then shown in the API docs (by Swagger UI).
And that same information from the models that is included in OpenAPI is what can be used to **generate the client code**.
### Generate a TypeScript Client
Now that we have the app with the models, we can generate the client code for the frontend.
#### Install `openapi-ts`
You can install `openapi-ts` in your frontend code with:
<divclass="termy">
That information is available in the app's **OpenAPI schema**, and then shown in the API docs.
```console
$ npm install @hey-api/openapi-ts --save-dev
That same information from the models that is included in OpenAPI is what can be used to **generate the client code**.
---> 100%
```
</div>
#### Generate Client Code
To generate the client code you can use the command line application `openapi-ts` that would now be installed.
Because it is installed in the local project, you probably wouldn't be able to call that command directly, but you would put it on your `package.json` file.
This will generate a TypeScript SDK in `./src/client`.
That command will generate code in `./src/client` and will use `axios` (the frontend HTTP library) internally.
You can learn how to <ahref="https://heyapi.dev/openapi-ts/get-started"class="external-link"target="_blank">install `@hey-api/openapi-ts`</a> and read about the <ahref="https://heyapi.dev/openapi-ts/output"class="external-link"target="_blank">generated output</a> on their website.
### Try Out the Client Code
### Using the SDK { #using-the-sdk }
Now you can import and use the client code, it could look like this, notice that you get autocompletion for the methods:
Now you can import and use the client code. It could look like this, notice that you get autocompletion for the methods:
You can **modify** the way these operation IDs are **generated** to make them simpler and have **simpler method names** in the clients.
In this case you will have to ensure that each operation ID is **unique** in some other way.
In this case, you will have to ensure that each operation ID is **unique** in some other way.
For example, you could make sure that each *path operation* has a tag, and then generate the operation ID based on the **tag** and the *path operation***name** (the function name).
### Custom Generate Unique ID Function
### Custom Generate Unique ID Function { #custom-generate-unique-id-function }
FastAPI uses a **unique ID** for each *path operation*, it is used for the **operation ID** and also for the names of any needed custom models, for requests or responses.
FastAPI uses a **unique ID** for each *path operation*, which is used for the **operation ID** and also for the names of any needed custom models, for requests or responses.
You can customize that function. It takes an `APIRoute` and outputs a string.
@ -186,15 +147,15 @@ You can then pass that custom function to **FastAPI** as the `generate_unique_id
As you see, the method names now have the tag and then the function name, now they don't include information from the URL path and the HTTP operation.
### Preprocess the OpenAPI Specification for the Client Generator
### Preprocess the OpenAPI Specification for the Client Generator { #preprocess-the-openapi-specification-for-the-client-generator }
The generated code still has some **duplicated information**.
@ -202,7 +163,7 @@ We already know that this method is related to the **items** because that word i
We will probably still want to keep it for OpenAPI in general, as that will ensure that the operation IDs are **unique**.
But for the generated client we could **modify** the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and **cleaner**.
But for the generated client, we could **modify** the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and **cleaner**.
We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
@ -218,35 +179,21 @@ We could download the OpenAPI JSON to a file `openapi.json` and then we could **
With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names.
### Generate a TypeScript Client with the Preprocessed OpenAPI
Now as the end result is in a file `openapi.json`, you would modify the `package.json` to use that local file, for example:
When using the automatically generated clients you would get **autocompletion** for:
When using the automatically generated clients, you would get **autocompletion** for:
* Methods.
* Request payloads in the body, query parameters, etc.
@ -256,6 +203,6 @@ You would also have **inline errors** for everything.
And whenever you update the backend code, and **regenerate** the frontend, it would have any new *path operations* available as methods, the old ones removed, and any other change would be reflected on the generated code. 🤓
This also means that if something changed it will be **reflected** on the client code automatically. And if you **build** the client it will error out if you have any **mismatch** in the data used.
This also means that if something changed, it will be **reflected** on the client code automatically. And if you **build** the client, it will error out if you have any **mismatch** in the data used.
So, you would **detect many errors** very early in the development cycle instead of having to wait for the errors to show up to your final users in production and then trying to debug where the problem is. ✨
The main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} should be enough to give you a tour through all the main features of **FastAPI**.
@ -14,7 +14,7 @@ And it's possible that for your use case, the solution is in one of them.
///
## Read the Tutorial first
## Read the Tutorial first { #read-the-tutorial-first }
You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank}.
As **FastAPI** is based on Starlette and implements the <abbrtitle="Asynchronous Server Gateway Interface">ASGI</abbr> specification, you can use any ASGI middleware.
Enforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks.
@ -68,10 +68,11 @@ Enforces that all incoming requests have a correctly set `Host` header, in order
The following arguments are supported:
* `allowed_hosts` - A list of domain names that should be allowed as hostnames. Wildcard domains such as `*.example.com` are supported for matching subdomains. To allow any hostname either use `allowed_hosts=["*"]` or omit the middleware.
* `www_redirect` - If set to True, requests to non-www versions of the allowed hosts will be redirected to their www counterparts. Defaults to `True`.
If an incoming request does not validate correctly then a `400` response will be sent.
## `GZipMiddleware`
## `GZipMiddleware` { #gzipmiddleware }
Handles GZip responses for any request that includes `"gzip"` in the `Accept-Encoding` header.
@ -84,7 +85,7 @@ The following arguments are supported:
* `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`.
* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes.
You could create an API with a *path operation* that could trigger a request to an *external API* created by someone else (probably the same developer that would be *using* your API).
@ -6,7 +6,7 @@ The process that happens when your API app calls the *external API* is named a "
In this case, you could want to document how that external API *should* look like. What *path operation* it should have, what body it should expect, what response it should return, etc.
## An app with callbacks
## An app with callbacks { #an-app-with-callbacks }
Let's see all this with an example.
@ -23,7 +23,7 @@ Then your API will (let's imagine):
* Send a notification back to the API user (the external developer).
* This will be done by sending a POST request (from *your API*) to some *external API* provided by that external developer (this is the "callback").
## The normal **FastAPI** app
## The normal **FastAPI** app { #the-normal-fastapi-app }
Let's first see how the normal API app would look like before adding the callback.
@ -41,7 +41,7 @@ The `callback_url` query parameter uses a Pydantic <a href="https://docs.pydanti
The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next.
## Documenting the callback
## Documenting the callback { #documenting-the-callback }
The actual callback code will depend heavily on your own API app.
@ -70,7 +70,7 @@ When implementing the callback yourself, you could use something like <a href="h
///
## Write the callback documentation code
## Write the callback documentation code { #write-the-callback-documentation-code }
This code won't be executed in your app, we only need it to *document* how that *external API* should look like.
@ -86,13 +86,13 @@ Temporarily adopting this point of view (of the *external developer*) can help y
///
### Create a callback `APIRouter`
### Create a callback `APIRouter` { #create-a-callback-apirouter }
First create a new `APIRouter` that will contain one or more callbacks.
### Create the callback *path operation* { #create-the-callback-path-operation }
To create the callback *path operation* use the same `APIRouter` you created above.
@ -108,7 +108,7 @@ There are 2 main differences from a normal *path operation*:
* It doesn't need to have any actual code, because your app will never call this code. It's only used to document the *external API*. So, the function could just have `pass`.
* The *path* can contain an <ahref="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression"class="external-link"target="_blank">OpenAPI 3 expression</a> (see more below) where it can use variables with parameters and parts of the original request sent to *your API*.
### The callback path expression
### The callback path expression { #the-callback-path-expression }
The callback *path* can have an <ahref="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression"class="external-link"target="_blank">OpenAPI 3 expression</a> that can contain parts of the original request sent to *your API*.
@ -163,7 +163,7 @@ Notice how the callback URL used contains the URL received as a query parameter
///
### Add the callback router
### Add the callback router { #add-the-callback-router }
At this point you have the *callback path operation(s)* needed (the one(s) that the *external developer* should implement in the *external API*) in the callback router you created above.
@ -177,7 +177,7 @@ Notice that you are not passing the router itself (`invoices_callback_router`) t
///
### Check the docs
### Check the docs { #check-the-docs }
Now you can start your app and go to <ahref="http://127.0.0.1:8000/docs"class="external-link"target="_blank">http://127.0.0.1:8000/docs</a>.
There are cases where you want to tell your API **users** that your app could call *their* app (sending a request) with some data, normally to **notify** of some type of **event**.
@ -6,7 +6,7 @@ This means that instead of the normal process of your users sending requests to
This is normally called a **webhook**.
## Webhooks steps
## Webhooks steps { #webhooks-steps }
The process normally is that **you define** in your code what is the message that you will send, the **body of the request**.
@ -16,7 +16,7 @@ And **your users** define in some way (for example in a web dashboard somewhere)
All the **logic** about how to register the URLs for webhooks and the code to actually send those requests is up to you. You write it however you want to in **your own code**.
## Documenting webhooks with **FastAPI** and OpenAPI
## Documenting webhooks with **FastAPI** and OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the types of HTTP operations that your app can send (e.g. `POST`, `PUT`, etc.) and the request **bodies** that your app would send.
@ -28,7 +28,7 @@ Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0`
///
## An app with webhooks
## An app with webhooks { #an-app-with-webhooks }
When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`.
@ -46,7 +46,7 @@ Notice that with webhooks you are actually not declaring a *path* (like `/items/
This is because it is expected that **your users** would define the actual **URL path** where they want to receive the webhook request in some other way (e.g. a web dashboard).
### Check the docs
### Check the docs { #check-the-docs }
Now you can start your app and go to <ahref="http://127.0.0.1:8000/docs"class="external-link"target="_blank">http://127.0.0.1:8000/docs</a>.
### Using the *path operation function* name as the operationId
### Using the *path operation function* name as the operationId { #using-the-path-operation-function-name-as-the-operationid }
If you want to use your APIs' function names as `operationId`s, you can iterate over all of them and override each *path operation's*`operation_id` using their `APIRoute.name`.
@ -36,13 +36,13 @@ Even if they are in different modules (Python files).
///
## Exclude from OpenAPI
## Exclude from OpenAPI { #exclude-from-openapi }
To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`:
You probably have seen how to declare the `response_model` and `status_code` for a *path operation*.
@ -62,7 +62,7 @@ You can also declare additional responses with their models, status codes, etc.
There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
## OpenAPI Extra
## OpenAPI Extra { #openapi-extra }
When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema.
@ -88,7 +88,7 @@ If you only need to declare additional responses, a more convenient way to do it
You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`.
### OpenAPI Extensions
### OpenAPI Extensions { #openapi-extensions }
This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
@ -129,7 +129,7 @@ And if you see the resulting OpenAPI (at `/openapi.json` in your API), you will
The dictionary in `openapi_extra` will be deeply merged with the automatically generated OpenAPI schema for the *path operation*.
@ -145,7 +145,7 @@ In this example, we didn't declare any Pydantic model. In fact, the request body
Nevertheless, we can declare the expected schema for the request body.
### Custom OpenAPI content type
### Custom OpenAPI content type { #custom-openapi-content-type }
Using this same trick, you could use a Pydantic model to define the JSON Schema that is then included in the custom OpenAPI schema section for the *path operation*.
# Return a Response Directly { #return-a-response-directly }
When you create a **FastAPI***path operation* you can normally return any data from it: a `dict`, a `list`, a Pydantic model, a database model, etc.
@ -10,7 +10,7 @@ But you can return a `JSONResponse` directly from your *path operations*.
It might be useful, for example, to return custom headers or cookies.
## Return a `Response`
## Return a `Response` { #return-a-response }
In fact, you can return any `Response` or any sub-class of it.
@ -26,7 +26,7 @@ It won't do any data conversion with Pydantic models, it won't convert the conte
This gives you a lot of flexibility. You can return any data type, override any data declaration or validation, etc.
## Using the `jsonable_encoder` in a `Response`
## Using the `jsonable_encoder` in a `Response` { #using-the-jsonable-encoder-in-a-response }
Because **FastAPI** doesn't make any changes to a `Response` you return, you have to make sure its contents are ready for it.
@ -44,7 +44,7 @@ You could also use `from starlette.responses import JSONResponse`.
///
## Returning a custom `Response`
## Returning a custom `Response` { #returning-a-custom-response }
The example above shows all the parts you need, but it's not very useful yet, as you could have just returned the `item` directly, and **FastAPI** would put it in a `JSONResponse` for you, converting it to a `dict`, etc. All that by default.
@ -56,9 +56,9 @@ You could put your XML content in a string, put that in a `Response`, and return
## Use a `Response` parameter { #use-a-response-parameter }
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies).
@ -16,7 +16,7 @@ And if you declared a `response_model`, it will still be used to filter and conv
You can also declare the `Response` parameter in dependencies, and set headers (and cookies) in them.
## Return a `Response` directly
## Return a `Response` directly { #return-a-response-directly }
You can also add headers when you return a `Response` directly.
@ -34,7 +34,7 @@ And as the `Response` can be used frequently to set headers and cookies, **FastA
///
## Custom Headers
## Custom Headers { #custom-headers }
Keep in mind that custom proprietary headers can be added <ahref="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers"class="external-link"target="_blank">using the 'X-' prefix</a>.
@ -26,7 +26,7 @@ When you try to open the URL for the first time (or click the "Execute" button i
<imgsrc="/img/tutorial/security/image12.png">
## Check the username
## Check the username { #check-the-username }
Here's a more complete example.
@ -52,7 +52,7 @@ if not (credentials.username == "stanleyjobson") or not (credentials.password ==
But by using the `secrets.compare_digest()` it will be secure against a type of attacks called "timing attacks".
### Timing Attacks
### Timing Attacks { #timing-attacks }
But what's a "timing attack"?
@ -80,19 +80,19 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "Incorrect username or password".
#### The time to answer helps the attackers
#### The time to answer helps the attackers { #the-time-to-answer-helps-the-attackers }
At that point, by noticing that the server took some microseconds longer to send the "Incorrect username or password" response, the attackers will know that they got _something_ right, some of the initial letters were right.
And then they can try again knowing that it's probably something more similar to `stanleyjobsox` than to `johndoe`.
#### A "professional" attack
#### A "professional" attack { #a-professional-attack }
Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And they would get just one extra correct letter at a time.
But doing that, in some minutes or hours the attackers would have guessed the correct username and password, with the "help" of our application, just using the time taken to answer.
#### Fix it with `secrets.compare_digest()`
#### Fix it with `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
But in our code we are actually using `secrets.compare_digest()`.
@ -100,7 +100,7 @@ In short, it will take the same time to compare `stanleyjobsox` to `stanleyjobso
That way, using `secrets.compare_digest()` in your application code, it will be safe against this whole range of security attacks.
### Return the error
### Return the error { #return-the-error }
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}.
@ -12,7 +12,7 @@ And it's possible that for your use case, the solution is in one of them.
///
## Read the Tutorial first
## Read the Tutorial first { #read-the-tutorial-first }
The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}.
You can use OAuth2 scopes directly with **FastAPI**, they are integrated to work seamlessly.
This would allow you to have a more fine-grained permission system, following the OAuth2 standard, integrated into your OpenAPI application (and the API docs).
OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, Twitter, etc. They use it to provide specific permissions to users and applications.
OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, X (Twitter), etc. They use it to provide specific permissions to users and applications.
Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that application is using OAuth2 with scopes.
Every time you "log in with" Facebook, Google, GitHub, Microsoft, X (Twitter), that application is using OAuth2 with scopes.
In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application.
@ -26,7 +26,7 @@ But if you know you need it, or you are curious, keep reading.
///
## OAuth2 scopes and OpenAPI
## OAuth2 scopes and OpenAPI { #oauth2-scopes-and-openapi }
The OAuth2 specification defines "scopes" as a list of strings separated by spaces.
@ -58,15 +58,15 @@ For OAuth2 they are just strings.
///
## Global view
## Global view { #global-view }
First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes:
We now verify that all the scopes required, by this dependency and all the dependants (including *path operations*), are included in the scopes provided in the token received, otherwise raise an `HTTPException`.
For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.
## Dependency tree and scopes { #dependency-tree-and-scopes }
Let's review again this dependency tree and the scopes.
@ -223,7 +223,7 @@ All depending on the `scopes` declared in each *path operation* and each depende
///
## More details about `SecurityScopes`
## More details about `SecurityScopes` { #more-details-about-securityscopes }
You can use `SecurityScopes` at any point, and in multiple places, it doesn't have to be at the "root" dependency.
@ -233,7 +233,7 @@ Because the `SecurityScopes` will have all the scopes declared by dependants, yo
They will be checked independently for each *path operation*.
## Check it
## Check it { #check-it }
If you open the API docs, you can authenticate and specify which scopes you want to authorize.
@ -245,7 +245,7 @@ And if you select the scope `me` but not the scope `items`, you will be able to
That's what would happen to a third party application that tried to access one of these *path operations* with a token provided by a user, depending on how many permissions the user gave the application.
## About third party integrations
## About third party integrations { #about-third-party-integrations }
In this example we are using the OAuth2 "password" flow.
@ -269,6 +269,6 @@ But in the end, they are implementing the same OAuth2 standard.
**FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`.
## `Security` in decorator `dependencies`
## `Security` in decorator `dependencies` { #security-in-decorator-dependencies }
The same way you can define a `list` of `Depends` in the decorator's `dependencies` parameter (as explained in [Dependencies in path operation decorators](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), you could also use `Security` with `scopes` there.
# Settings and Environment Variables { #settings-and-environment-variables }
In many cases your application could need some external settings or configurations, for example secret keys, database credentials, credentials for email services, etc.
@ -12,17 +12,17 @@ To understand environment variables you can read [Environment Variables](../envi
///
## Types and validation
## Types and validation { #types-and-validation }
These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS).
That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code.
## Pydantic `Settings`
## Pydantic `Settings` { #pydantic-settings }
Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with <ahref="https://docs.pydantic.dev/latest/concepts/pydantic_settings/"class="external-link"target="_blank">Pydantic: Settings management</a>.
First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package:
@ -52,7 +52,7 @@ In Pydantic v1 it came included with the main package. Now it is distributed as
///
### Create the `Settings` object
### Create the `Settings` object { #create-the-settings-object }
Import `BaseSettings` from Pydantic and create a sub-class, very much like with a Pydantic model.
@ -88,13 +88,13 @@ Then, when you create an instance of that `Settings` class (in this case, in the
Next it will convert and validate the data. So, when you use that `settings` object, you will have data of the types you declared (e.g. `items_per_user` will be an `int`).
### Use the `settings`
### Use the `settings` { #use-the-settings }
Then you can use the new `settings` object in your application:
Next, you would run the server passing the configurations as environment variables, for example you could set an `ADMIN_EMAIL` and `APP_NAME` with:
@ -120,7 +120,7 @@ The `app_name` would be `"ChimichangApp"`.
And the `items_per_user` would keep its default value of `50`.
## Settings in another module
## Settings in another module { #settings-in-another-module }
You could put those settings in another module file as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}.
@ -138,13 +138,13 @@ You would also need a file `__init__.py` as you saw in [Bigger Applications - Mu
///
## Settings in a dependency
## Settings in a dependency { #settings-in-a-dependency }
In some occasions it might be useful to provide the settings from a dependency, instead of having a global object with `settings` that is used everywhere.
This could be especially useful during testing, as it's very easy to override a dependency with your own custom settings.
### The config file
### The config file { #the-config-file }
Coming from the previous example, your `config.py` file could look like:
@ -152,7 +152,7 @@ Coming from the previous example, your `config.py` file could look like:
Notice that now we don't create a default instance `settings = Settings()`.
### The main app file
### The main app file { #the-main-app-file }
Now we create a dependency that returns a new `config.Settings()`.
@ -170,7 +170,7 @@ And then we can require it from the *path operation function* as a dependency an
### Settings and testing { #settings-and-testing }
Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`:
@ -180,7 +180,7 @@ In the dependency override we set a new value for the `admin_email` when creatin
Then we can test that it is used.
## Reading a `.env` file
## Reading a `.env` file { #reading-a-env-file }
If you have many settings that possibly change a lot, maybe in different environments, it might be useful to put them on a file and then read them from it as if they were environment variables.
@ -202,7 +202,7 @@ For this to work, you need to `pip install python-dotenv`.
### Read settings from `.env` { #read-settings-from-env }
And then update your `config.py` with:
@ -247,7 +247,7 @@ In Pydantic version 1 the configuration was done in an internal class `Config`,
Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use.
### Creating the `Settings` only once with `lru_cache`
### Creating the `Settings` only once with `lru_cache` { #creating-the-settings-only-once-with-lru-cache }
Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request.
@ -274,7 +274,7 @@ But as we are using the `@lru_cache` decorator on top, the `Settings` object wil
Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again.
`@lru_cache` modifies the function it decorates to return the same value that was returned the first time, instead of computing it again, executing the code of the function every time.
@ -337,7 +337,7 @@ That way, it behaves almost as if it was just a global variable. But as it uses
`@lru_cache` is part of `functools` which is part of Python's standard library, you can read more about it in the <ahref="https://docs.python.org/3/library/functools.html#functools.lru_cache"class="external-link"target="_blank">Python docs for `@lru_cache`</a>.
## Recap
## Recap { #recap }
You can use Pydantic Settings to handle the settings or configurations for your application, with all the power of Pydantic models.
# Sub Applications - Mounts { #sub-applications-mounts }
If you need to have two independent FastAPI applications, with their own independent OpenAPI and their own docs UIs, you can have a main app and "mount" one (or more) sub-application(s).
## Mounting a **FastAPI** application
## Mounting a **FastAPI** application { #mounting-a-fastapi-application }
"Mounting" means adding a completely "independent" application in a specific path, that then takes care of handling everything under that path, with the _path operations_ declared in that sub-application.
### Check the automatic API docs { #check-the-automatic-api-docs }
Now, run the `fastapi` command with your file:
@ -56,7 +56,7 @@ You will see the automatic API docs for the sub-application, including only its
If you try interacting with any of the two user interfaces, they will work correctly, because the browser will be able to talk to each specific app or sub-app.
When you mount a sub-application as described above, FastAPI will take care of communicating the mount path for the sub-application using a mechanism from the ASGI specification called a `root_path`.
You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*.
@ -105,7 +105,7 @@ For example, with an ID of `42`, this would render:
<ahref="/items/42">
```
## Templates and static files
## Templates and static files { #templates-and-static-files }
You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`.
@ -121,6 +121,6 @@ In this example, it would link to a CSS file at `static/styles.css` with:
And because you are using `StaticFiles`, that CSS file would be served automatically by your **FastAPI** application at the URL `/static/styles.css`.
## More details
## More details { #more-details }
For more details, including how to test templates, check <ahref="https://www.starlette.io/templates/"class="external-link"target="_blank">Starlette's docs on templates</a>.
# Testing Dependencies with Overrides { #testing-dependencies-with-overrides }
## Overriding dependencies during testing
## Overriding dependencies during testing { #overriding-dependencies-during-testing }
There are some scenarios where you might want to override a dependency during testing.
@ -8,7 +8,7 @@ You don't want the original dependency to run (nor any of the sub-dependencies i
Instead, you want to provide a different dependency that will be used only during tests (possibly only some specific tests), and will provide a value that can be used where the value of the original dependency was used.
### Use cases: external service
### Use cases: external service { #use-cases-external-service }
An example could be that you have an external authentication provider that you need to call.
@ -20,7 +20,7 @@ You probably want to test the external provider once, but not necessarily call i
In this case, you can override the dependency that calls that provider, and use a custom dependency that returns a mock user, only for your tests.
### Use the `app.dependency_overrides` attribute
### Use the `app.dependency_overrides` attribute { #use-the-app-dependency-overrides-attribute }
For these cases, your **FastAPI** application has an attribute `app.dependency_overrides`, it is a simple `dict`.
You can read more details about the ["Running lifespan in tests in the official Starlette documentation site."](https://www.starlette.io/lifespan/#running-lifespan-in-tests)
For the deprecated `startup` and `shutdown` events, you can use the `TestClient` as follows:
# Using the Request Directly { #using-the-request-directly }
Up to now, you have been declaring the parts of the request that you need with their types.
@ -13,7 +13,7 @@ And by doing so, **FastAPI** is validating that data, converting it and generati
But there are situations where you might need to access the `Request` object directly.
## Details about the `Request` object
## Details about the `Request` object { #details-about-the-request-object }
As **FastAPI** is actually **Starlette** underneath, with a layer of several tools on top, you can use Starlette's <ahref="https://www.starlette.io/requests/"class="external-link"target="_blank">`Request`</a> object directly when you need to.
@ -23,7 +23,7 @@ Although any other parameter declared normally (for example, the body with a Pyd
But there are specific cases where it's useful to get the `Request` object.
## Use the `Request` object directly
## Use the `Request` object directly { #use-the-request-object-directly }
Let's imagine you want to get the client's IP address/host inside of your *path operation function*.
@ -43,7 +43,7 @@ The same way, you can declare any other parameter as normally, and additionally,
You can read more details about the <ahref="https://www.starlette.io/requests/"class="external-link"target="_blank">`Request` object in the official Starlette documentation site</a>.
You can use <ahref="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API"class="external-link"target="_blank">WebSockets</a> with **FastAPI**.
## Install `WebSockets`
## Install `WebSockets` { #install-websockets }
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `websockets`:
@ -16,9 +16,9 @@ $ pip install websockets
</div>
## WebSockets client
## WebSockets client { #websockets-client }
### In production
### In production { #in-production }
In your production system, you probably have a frontend created with a modern framework like React, Vue.js or Angular.
@ -40,7 +40,7 @@ But it's the simplest way to focus on the server-side of WebSockets and have a w
In your **FastAPI** application, create a `websocket`:
@ -54,7 +54,7 @@ You could also use `from starlette.websockets import WebSocket`.
///
## Await for messages and send messages
## Await for messages and send messages { #await-for-messages-and-send-messages }
In your WebSocket route you can `await` for messages and send messages.
@ -62,7 +62,7 @@ In your WebSocket route you can `await` for messages and send messages.
You can receive and send binary, text, and JSON data.
## Try it
## Try it { #try-it }
If your file is named `main.py`, run your application with:
@ -96,7 +96,7 @@ You can send (and receive) many messages:
And all of them will use the same WebSocket connection.
## Using `Depends` and others
## Using `Depends` and others { #using-depends-and-others }
In WebSocket endpoints you can import from `fastapi` and use:
@ -119,7 +119,7 @@ You can use a closing code from the <a href="https://tools.ietf.org/html/rfc6455
///
### Try the WebSockets with dependencies
### Try the WebSockets with dependencies { #try-the-websockets-with-dependencies }
If your file is named `main.py`, run your application with:
@ -150,7 +150,7 @@ With that you can connect the WebSocket and then send and receive messages:
<imgsrc="/img/tutorial/websockets/image05.png">
## Handling disconnections and multiple clients
## Handling disconnections and multiple clients { #handling-disconnections-and-multiple-clients }
When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example.
@ -178,7 +178,7 @@ If you need something easy to integrate with FastAPI but that is more robust, su
///
## More info
## More info { #more-info }
To learn more about the options, check Starlette's documentation for:
# Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others }
You can mount WSGI applications as you saw with [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}.
For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI application, for example, Flask, Django, etc.
## Using `WSGIMiddleware`
## Using `WSGIMiddleware` { #using-wsgimiddleware }
You need to import `WSGIMiddleware`.
@ -14,7 +14,7 @@ And then mount that under a path.
# Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons }
What inspired **FastAPI**, how it compares to alternatives and what it learned from them.
## Intro
## Intro { #intro }
**FastAPI** wouldn't exist if not for the previous work of others.
@ -12,9 +12,9 @@ I have been avoiding the creation of a new framework for several years. First I
But at some point, there was no other option than creating something that provided all these features, taking the best ideas from previous tools, and combining them in the best way possible, using language features that weren't even available before (Python 3.6+ type hints).
It's the most popular Python framework and is widely trusted. It is used to build systems like Instagram.
@ -22,7 +22,7 @@ It's relatively tightly coupled with relational databases (like MySQL or Postgre
It was created to generate the HTML in the backend, not to create APIs used by a modern frontend (like React, Vue.js and Angular) or by other systems (like <abbrtitle="Internet of Things">IoT</abbr> devices) communicating with it.
There are several Flask REST frameworks, but after investing the time and work into investigating them, I found that many are discontinued or abandoned, with several standing issues that made them unfit.
One of the main features needed by API systems is data "<abbrtitle="also called marshalling, conversion">serialization</abbr>" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.
@ -153,7 +153,7 @@ Use code to define "schemas" that provide data types and validation, automatical
Hug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same.
@ -351,7 +351,7 @@ Hug inspired **FastAPI** to declare a `response` parameter in functions to set h
Starlette is a lightweight <abbrtitle="The new standard for building asynchronous Python web applications">ASGI</abbr> framework/toolkit, which is ideal for building high-performance asyncio services.
@ -462,7 +462,7 @@ So, anything that you can do with Starlette, you can do it directly with **FastA
Uvicorn is a lightning-fast ASGI server, built on uvloop and httptools.
@ -480,6 +480,6 @@ Check more details in the [Deployment](deployment/index.md){.internal-link targe
///
## Benchmarks and speed
## Benchmarks and speed { #benchmarks-and-speed }
To understand, compare, and see the difference between Uvicorn, Starlette and FastAPI, check the section about [Benchmarks](benchmarks.md){.internal-link target=_blank}.
If your application (somehow) doesn't have to communicate with anything else and wait for it to respond, use `async def`.
If your application (somehow) doesn't have to communicate with anything else and wait for it to respond, use `async def`, even if you don't need to use `await` inside.
---
@ -54,7 +54,7 @@ Anyway, in any of the cases above, FastAPI will still work asynchronously and be
But by following the steps above, it will be able to do some performance optimizations.
## Technical Details
## Technical Details { #technical-details }
Modern versions of Python have support for **"asynchronous code"** using something called **"coroutines"**, with **`async` and `await`** syntax.
@ -64,7 +64,7 @@ Let's see that phrase by parts in the sections below:
* **`async` and `await`**
* **Coroutines**
## Asynchronous Code
## Asynchronous Code { #asynchronous-code }
Asynchronous code just means that the language 💬 has a way to tell the computer / program 🤖 that at some point in the code, it 🤖 will have to wait for *something else* to finish somewhere else. Let's say that *something else* is called "slow-file" 📝.
@ -93,7 +93,7 @@ Instead of that, by being an "asynchronous" system, once finished, the task can
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
### Concurrency and Burgers { #concurrency-and-burgers }
This idea of **asynchronous** code described above is also sometimes called **"concurrency"**. It is different from **"parallelism"**.
@ -103,7 +103,7 @@ But the details between *concurrency* and *parallelism* are quite different.
To see the difference, imagine the following story about burgers:
### Concurrent Burgers
### Concurrent 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. 😍
@ -163,7 +163,7 @@ So you wait for your crush to finish the story (finish the current work ⏯ / ta
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
### Parallel Burgers { #parallel-burgers }
Now let's imagine these aren't "Concurrent Burgers", but "Parallel Burgers".
@ -233,7 +233,7 @@ 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 run errands at the bank 🏦.
### Burger Conclusion
### Burger Conclusion { #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 ⏸🔀⏯.
@ -253,7 +253,7 @@ And that's the same level of performance 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 <ahref="https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1"class="external-link"target="_blank">(all thanks to Starlette)</a>.
### Is concurrency better than parallelism?
### Is concurrency better than parallelism? { #is-concurrency-better-than-parallelism }
Nope! That's not the moral of the story.
@ -290,7 +290,7 @@ For example:
* **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 advantage of concurrency that is very common for web development (the same main attraction of NodeJS).
@ -300,7 +300,7 @@ That, plus the simple fact that Python is the main language for **Data Science**
To see how to achieve this parallelism in production see the section about [Deployment](deployment/index.md){.internal-link target=_blank}.
## `async` and `await`
## `async` and `await` { #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.
@ -349,7 +349,7 @@ async def read_burgers():
return burgers
```
### More technical details
### More technical details { #more-technical-details }
You might have noticed that `await` can only be used inside of functions defined with `async def`.
@ -361,7 +361,7 @@ If you are working with **FastAPI** you don't have to worry about that, because
But if you want to use `async` / `await` without FastAPI, you can do it as well.
### Write your own async code
### Write your own async code { #write-your-own-async-code }
Starlette (and **FastAPI**) are based on <ahref="https://anyio.readthedocs.io/en/stable/"class="external-link"target="_blank">AnyIO</a>, which makes it compatible with both Python's standard library <ahref="https://docs.python.org/3/library/asyncio-task.html"class="external-link"target="_blank">asyncio</a> and <ahref="https://trio.readthedocs.io/en/stable/"class="external-link"target="_blank">Trio</a>.
@ -371,7 +371,7 @@ And even if you were not using FastAPI, you could also write your own async appl
I created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: <ahref="https://asyncer.tiangolo.com/"class="external-link"target="_blank">Asyncer</a>. It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code.
### Other forms of asynchronous code
### Other forms of asynchronous code { #other-forms-of-asynchronous-code }
This style of using `async` and `await` is relatively new in the language.
@ -383,15 +383,15 @@ But before that, handling asynchronous code was quite more complex and difficult
In previous versions of Python, you could have used threads or <ahref="https://www.gevent.org/"class="external-link"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 leads to <ahref="http://callbackhell.com/"class="external-link"target="_blank">callback hell</a>.
In previous versions of NodeJS / Browser JavaScript, you would have used "callbacks". Which leads to "callbackhell".
## Coroutines
## Coroutines { #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
## Conclusion { #conclusion }
Let's see the same phrase from above:
@ -401,7 +401,7 @@ That should make more sense now. ✨
All that is what powers FastAPI (through Starlette) and what makes it have such an impressive performance.
## Very Technical Details
## Very Technical Details { #very-technical-details }
/// warning
@ -413,7 +413,7 @@ If you have quite some technical knowledge (coroutines, threads, blocking, etc.)
When you declare a *path operation function* with normal `def` instead of `async def`, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server).
@ -421,15 +421,15 @@ If you are coming from another async framework that does not work in the way des
Still, in both situations, chances are that **FastAPI** will [still be faster](index.md#performance){.internal-link target=_blank} than (or at least comparable to) your previous framework.
### Dependencies
### Dependencies { #dependencies }
The same applies for [dependencies](tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool.
### Sub-dependencies
### Sub-dependencies { #sub-dependencies }
You can have multiple dependencies and [sub-dependencies](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited".
### Other utility functions
### Other utility functions { #other-utility-functions }
Any other utility function that you call directly can be created with normal `def` or `async def` and FastAPI won't affect the way you call it.
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <ahref="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).
But when checking benchmarks and comparisons you should keep the following in mind.
## Benchmarks and speed
## Benchmarks and speed { #benchmarks-and-speed }
When you check the benchmarks, it is common to see several tools of different types compared as equivalent.
@ -181,6 +181,28 @@ as Uvicorn by default will use the port `8000`, the documentation on port `8008`
### Translations
/// warning | Attention
**Update on Translations**
We're updating the way we handle documentation translations.
Until now, we invited community members to translate pages via pull requests, which were then reviewed by at least two native speakers. While this has helped bring FastAPI to many more users, we’ve also run into several challenges - some languages have only a few translated pages, others are outdated and hard to maintain over time.
To improve this, we’re working on automation tools 🤖 to manage translations more efficiently. Once ready, documentation will be machine-translated and still reviewed by at least two native speakers ✅ before publishing. This will allow us to keep translations up-to-date while reducing the review burden on maintainers.
What’s changing now:
* 🚫 We’re no longer accepting new community-submitted translation PRs.
* ⏳ Existing open PRs will be reviewed and can still be merged if completed within the next 3 weeks (since July 11 2025).
* 🌐 In the future, we will only support languages where at least three active native speakers are available to review and maintain translations.
This transition will help us keep translations more consistent and timely while better supporting our contributors 🙌. Thank you to everyone who has contributed so far — your help has been invaluable! 💖
///
Help with translations is VERY MUCH appreciated! And it can't be done without the help from the community. 🌎 🚀
Here are the steps to help with translations.
@ -293,30 +315,47 @@ Now you can translate it all and see how it looks as you save the file.
Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc.
#### Request a New Language
Let's say that you want to request translations for a language that is not yet translated, not even some pages. For example, Latin.
If there is no discussion for that language, you can start by requesting the new language. For that, you can follow these steps:
* Create a new discussion following the template.
* Get a few native speakers to comment on the discussion and commit to help review translations for that language.
Once there are several people in the discussion, the FastAPI team can evaluate it and can make it an official translation.
Then the docs will be automatically translated using AI, and the team of native speakers can review the translation, and help tweak the AI prompts.
Once there's a new translation, for example if docs are updated or there's a new section, there will be a comment in the same discussion with the link to the new translation to review.
#### New Language
Let's say that you want to add translations for a language that is not yet translated, not even some pages.
/// note
Let's say you want to add translations for Creole, and it's not yet there in the docs.
These steps will be performed by the FastAPI team.
///
Checking the link from above, the code for "Creole" is `ht`.
Checking the link from above (List of ISO 639-1 codes), you can see that the 2-letter code for Latin is `la`.
The next step is to run the script to generate a new translation directory:
Now you can create a new directory for the new language, running the following script:
<divclass="termy">
```console
// Use the command new-lang, pass the language code as a CLI argument
$ python ./scripts/docs.py new-lang ht
$ python ./scripts/docs.py new-lang la
Successfully initialized: docs/ht
Successfully initialized: docs/la
```
</div>
Now you can check in your code editor the newly created directory `docs/ht/`.
Now you can check in your code editor the newly created directory `docs/la/`.
That command created a file `docs/ht/mkdocs.yml` with a simple config that inherits everything from the `en` version:
That command created a file `docs/la/mkdocs.yml` with a simple config that inherits everything from the `en` version:
```yaml
INHERIT: ../en/mkdocs.yml
@ -328,11 +367,11 @@ You could also simply create that file with those contents manually.
///
That command also created a dummy file `docs/ht/index.md` for the main page, you can start by translating that one.
That command also created a dummy file `docs/la/index.md` for the main page, you can start by translating that one.
You can continue with the previous instructions for an "Existing Language" for that process.
You can make the first pull request with those two files, `docs/ht/mkdocs.yml` and `docs/ht/index.md`. 🎉
You can make the first pull request with those two files, `docs/la/mkdocs.yml` and `docs/la/index.md`. 🎉
Some cloud providers ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**.
@ -12,7 +12,5 @@ And it shows their true commitment to FastAPI and its **community** (you), as th
You might want to try their services and follow their guides:
When deploying a **FastAPI** application, or actually, any type of web API, there are several concepts that you probably care about, and using them you can find the **most appropriate** way to **deploy your application**.
@ -23,7 +23,7 @@ In the next chapters, I'll give you more **concrete recipes** to deploy FastAPI
But for now, let's check these important **conceptual ideas**. These concepts also apply to any other type of web API. 💡
## Security - HTTPS
## Security - HTTPS { #security-https }
In the [previous chapter about HTTPS](https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API.
@ -31,7 +31,7 @@ We also saw that HTTPS is normally provided by a component **external** to your
And there has to be something in charge of **renewing the HTTPS certificates**, it could be the same component or it could be something different.
### Example Tools for HTTPS
### Example Tools for HTTPS { #example-tools-for-https }
Some of the tools you could use as a TLS Termination Proxy are:
@ -55,19 +55,19 @@ I'll show you some concrete examples in the next chapters.
Then the next concepts to consider are all about the program running your actual API (e.g. Uvicorn).
## Program and Process
## Program and Process { #program-and-process }
We will talk a lot about the running "**process**", so it's useful to have clarity about what it means, and what's the difference with the word "**program**".
### What is a Program
### What is a Program { #what-is-a-program }
The word **program** is commonly used to describe many things:
* The **code** that you write, the **Python files**.
* The **file** that can be **executed** by the operating system, for example: `python`, `python.exe` or `uvicorn`.
* A particular program while it is **running** on the operating system, using the CPU, and storing things on memory. This is also called a **process**.
* A particular program while it is **running** on the operating system, using the CPU, and storing things in memory. This is also called a **process**.
### What is a Process
### What is a Process { #what-is-a-process }
The word **process** is normally used in a more specific way, only referring to the thing that is running in the operating system (like in the last point above):
@ -88,11 +88,11 @@ And, for example, you will probably see that there are multiple processes runnin
Now that we know the difference between the terms **process** and **program**, let's continue talking about deployments.
## Running on Startup
## Running on Startup { #running-on-startup }
In most cases, when you create a web API, you want it to be **always running**, uninterrupted, so that your clients can always access it. This is of course, unless you have a specific reason why you want it to run only in certain situations, but most of the time you want it constantly running and **available**.
### In a Remote Server
### In a Remote Server { #in-a-remote-server }
When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is use `fastapi run` (which uses Uvicorn) or something similar, manually, the same way you do when developing locally.
@ -102,15 +102,15 @@ But if your connection to the server is lost, the **running process** will proba
And if the server is restarted (for example after updates, or migrations from the cloud provider) you probably **won't notice it**. And because of that, you won't even know that you have to restart the process manually. So, your API will just stay dead. 😱
### Run Automatically on Startup
### Run Automatically on Startup { #run-automatically-on-startup }
In general, you will probably want the server program (e.g. Uvicorn) to be started automatically on server startup, and without needing any **human intervention**, to have a process always running with your API (e.g. Uvicorn running your FastAPI app).
### Separate Program
### Separate Program { #separate-program }
To achieve this, you will normally have a **separate program** that would make sure your application is run on startup. And in many cases, it would also make sure other components or applications are also run, for example, a database.
### Example Tools to Run at Startup
### Example Tools to Run at Startup { #example-tools-to-run-at-startup }
Some examples of the tools that can do this job are:
@ -125,29 +125,29 @@ Some examples of the tools that can do this job are:
I'll give you more concrete examples in the next chapters.
## Restarts
## Restarts { #restarts }
Similar to making sure your application is run on startup, you probably also want to make sure it is **restarted** after failures.
### We Make Mistakes
### We Make Mistakes { #we-make-mistakes }
We, as humans, make **mistakes**, all the time. Software almost *always* has **bugs** hidden in different places. 🐛
And we as developers keep improving the code as we find those bugs and as we implement new features (possibly adding new bugs too 😅).
### Small Errors Automatically Handled
### Small Errors Automatically Handled { #small-errors-automatically-handled }
When building web APIs with FastAPI, if there's an error in our code, FastAPI will normally contain it to the single request that triggered the error. 🛡
The client will get a **500 Internal Server Error** for that request, but the application will continue working for the next requests instead of just crashing completely.
Nevertheless, there might be cases where we write some code that **crashes the entire application** making Uvicorn and Python crash. 💥
And still, you would probably not want the application to stay dead because there was an error in one place, you probably want it to **continue running** at least for the *path operations* that are not broken.
### Restart After Crash
### Restart After Crash { #restart-after-crash }
But in those cases with really bad errors that crash the running **process**, you would want an external component that is in charge of **restarting** the process, at least a couple of times...
@ -161,7 +161,7 @@ So let's focus on the main cases, where it could crash entirely in some particul
You would probably want to have the thing in charge of restarting your application as an **external component**, because by that point, the same application with Uvicorn and Python already crashed, so there's nothing in the same code of the same app that could do anything about it.
### Example Tools to Restart Automatically
### Example Tools to Restart Automatically { #example-tools-to-restart-automatically }
In most cases, the same tool that is used to **run the program on startup** is also used to handle automatic **restarts**.
@ -176,19 +176,19 @@ For example, this could be handled by:
* Handled internally by a cloud provider as part of their services
* Others...
## Replication - Processes and Memory
## Replication - Processes and Memory { #replication-processes-and-memory }
With a FastAPI application, using a server program like the `fastapi` command that runs Uvicorn, running it once in **one process** can serve multiple clients concurrently.
But in many cases, you will want to run several worker processes at the same time.
If you have more clients than what a single process can handle (for example if the virtual machine is not too big) and you have **multiple cores** in the server's CPU, then you could have **multiple processes** running with the same application at the same time, and distribute all the requests among them.
When you run **multiple processes** of the same API program, they are commonly called **workers**.
### Worker Processes and Ports
### Worker Processes and Ports { #worker-processes-and-ports }
Remember from the docs [About HTTPS](https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server?
@ -196,19 +196,19 @@ This is still true.
So, to be able to have **multiple processes** at the same time, there has to be a **single process listening on a port** that then transmits the communication to each worker process in some way.
### Memory per Process
### Memory per Process { #memory-per-process }
Now, when the program loads things in memory, for example, a machine learning model in a variable, or the contents of a large file in a variable, all that **consumes a bit of the memory (RAM)** of the server.
And multiple processes normally **don't share any memory**. This means that each running process has its own things, variables, and memory. And if you are consuming a large amount of memory in your code, **each process** will consume an equivalent amount of memory.
### Server Memory
### Server Memory { #server-memory }
For example, if your code loads a Machine Learning model with **1 GB in size**, when you run one process with your API, it will consume at least 1 GB of RAM. And if you start **4 processes** (4 workers), each will consume 1 GB of RAM. So in total, your API will consume **4 GB of RAM**.
And if your remote server or virtual machine only has 3 GB of RAM, trying to load more than 4 GB of RAM will cause problems. 🚨
### Multiple Processes - An Example
### Multiple Processes - An Example { #multiple-processes-an-example }
In this example, there's a **Manager Process** that starts and controls two **Worker Processes**.
@ -216,7 +216,7 @@ This Manager Process would probably be the one listening on the **port** in the
Those worker processes would be the ones running your application, they would perform the main computations to receive a **request** and return a **response**, and they would load anything you put in variables in RAM.
And of course, the same machine would probably have **other processes** running as well, apart from your application.
@ -224,7 +224,7 @@ An interesting detail is that the percentage of the **CPU used** by each process
If you have an API that does a comparable amount of computations every time and you have a lot of clients, then the **CPU utilization** will probably *also be stable* (instead of constantly going up and down quickly).
### Examples of Replication Tools and Strategies
### Examples of Replication Tools and Strategies { #examples-of-replication-tools-and-strategies }
There can be several approaches to achieve this, and I'll tell you more about specific strategies in the next chapters, for example when talking about Docker and containers.
@ -247,7 +247,7 @@ I'll tell you more about container images, Docker, Kubernetes, etc. in a future
///
## Previous Steps Before Starting
## Previous Steps Before Starting { #previous-steps-before-starting }
There are many cases where you want to perform some steps **before starting** your application.
@ -269,7 +269,7 @@ In that case, you wouldn't have to worry about any of this. 🤷
///
### Examples of Previous Steps Strategies
### Examples of Previous Steps Strategies { #examples-of-previous-steps-strategies }
This will **depend heavily** on the way you **deploy your system**, and it would probably be connected to the way you start programs, handling restarts, etc.
@ -285,7 +285,7 @@ I'll give you more concrete examples for doing this with containers in a future
///
## Resource Utilization
## Resource Utilization { #resource-utilization }
Your server(s) is (are) a **resource**, you can consume or **utilize**, with your programs, the computation time on the CPUs, and the RAM memory available.
@ -305,7 +305,7 @@ You could put an **arbitrary number** to target, for example, something **betwee
You can use simple tools like `htop` to see the CPU and RAM used in your server or the amount used by each process. Or you can use more complex monitoring tools, which may be distributed across servers, etc.
## Recap
## Recap { #recap }
You have been reading here some of the main concepts that you would probably need to keep in mind when deciding how to deploy your application:
# FastAPI in Containers - Docker { #fastapi-in-containers-docker }
When deploying FastAPI applications a common approach is to build a **Linux container image**. It's normally done using <ahref="https://www.docker.com/"class="external-link"target="_blank">**Docker**</a>. You can then deploy that container image in one of a few possible ways.
Containers (mainly Linux containers) are a very **lightweight** way to package applications including all their dependencies and necessary files while keeping them isolated from other containers (other applications or components) in the same system.
@ -42,7 +42,7 @@ This way, containers consume **little resources**, an amount comparable to runni
Containers also have their own **isolated** running processes (commonly just one process), file system, and network, simplifying deployment, security, development, etc.
## What is a Container Image
## What is a Container Image { #what-is-a-container-image }
A **container** is run from a **container image**.
@ -56,7 +56,7 @@ A container image is comparable to the **program** file and contents, e.g. `pyth
And the **container** itself (in contrast to the **container image**) is the actual running instance of the image, comparable to a **process**. In fact, a container is running only when it has a **process running** (and normally it's only a single process). The container stops when there's no process running in it.
## Container Images
## Container Images { #container-images }
Docker has been one of the main tools to create and manage **container images** and **containers**.
@ -79,7 +79,7 @@ So, you would run **multiple containers** with different things, like a database
All the container management systems (like Docker or Kubernetes) have these networking features integrated into them.
## Containers and Processes
## Containers and Processes { #containers-and-processes }
A **container image** normally includes in its metadata the default program or command that should be run when the **container** is started and the parameters to be passed to that program. Very similar to what would be if it was in the command line.
@ -91,7 +91,7 @@ A container normally has a **single process**, but it's also possible to start s
But it's not possible to have a running container without **at least one running process**. If the main process stops, the container stops.
## Build a Docker Image for FastAPI
## Build a Docker Image for FastAPI { #build-a-docker-image-for-fastapi }
Okay, let's build something now! 🚀
@ -103,7 +103,7 @@ This is what you would want to do in **most cases**, for example:
* When running on a **Raspberry Pi**
* Using a cloud service that would run a container image for you, etc.
Now in the same project directory create a file `Dockerfile` with:
@ -238,7 +238,7 @@ Make sure to **always** use the **exec form** of the `CMD` instruction, as expla
///
#### Use `CMD` - Exec Form
#### Use `CMD` - Exec Form { #use-cmd-exec-form }
The <ahref="https://docs.docker.com/reference/dockerfile/#cmd"class="external-link"target="_blank">`CMD`</a> Docker instruction can be written using two forms:
@ -262,7 +262,7 @@ You can read more about it in the <a href="https://docs.docker.com/reference/doc
This can be quite noticeable when using `docker compose`. See this Docker Compose FAQ section for more technical details: <ahref="https://docs.docker.com/compose/faq/#why-do-my-services-take-10-seconds-to-recreate-or-stop"class="external-link"target="_blank">Why do my services take 10 seconds to recreate or stop?</a>.
#### Directory Structure
#### Directory Structure { #directory-structure }
You should now have a directory structure like:
@ -275,7 +275,7 @@ You should now have a directory structure like:
└── requirements.txt
```
#### Behind a TLS Termination Proxy
#### Behind a TLS Termination Proxy { #behind-a-tls-termination-proxy }
If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn (through the FastAPI CLI) to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc.
@ -283,7 +283,7 @@ If you are running your container behind a TLS Termination Proxy (load balancer)
There's an important trick in this `Dockerfile`, we first copy the **file with the dependencies alone**, not the rest of the code. Let me tell you why is that.
@ -315,7 +315,7 @@ Then, near the end of the `Dockerfile`, we copy all the code. As this is what **
COPY ./app /code/app
```
### Build the Docker Image
### Build the Docker Image { #build-the-docker-image }
Now that all the files are in place, let's build the container image.
@ -340,7 +340,7 @@ In this case, it's the same current directory (`.`).
///
### Start the Docker Container
### Start the Docker Container { #start-the-docker-container }
You should be able to check it in your Docker container's URL, for example: <ahref="http://192.168.99.100/items/5?q=somequery"class="external-link"target="_blank">http://192.168.99.100/items/5?q=somequery</a> or <ahref="http://127.0.0.1/items/5?q=somequery"class="external-link"target="_blank">http://127.0.0.1/items/5?q=somequery</a> (or equivalent, using your Docker host).
@ -362,7 +362,7 @@ You will see something like:
{"item_id": 5, "q": "somequery"}
```
## Interactive API docs
## Interactive API docs { #interactive-api-docs }
Now you can go to <ahref="http://192.168.99.100/docs"class="external-link"target="_blank">http://192.168.99.100/docs</a> or <ahref="http://127.0.0.1/docs"class="external-link"target="_blank">http://127.0.0.1/docs</a> (or equivalent, using your Docker host).
@ -370,7 +370,7 @@ You will see the automatic interactive API documentation (provided by <a href="h
And you can also go to <ahref="http://192.168.99.100/redoc"class="external-link"target="_blank">http://192.168.99.100/redoc</a> or <ahref="http://127.0.0.1/redoc"class="external-link"target="_blank">http://127.0.0.1/redoc</a> (or equivalent, using your Docker host).
@ -378,7 +378,7 @@ You will see the alternative automatic documentation (provided by <a href="https
When you pass the file to `fastapi run` it will detect automatically that it is a single file and not part of a package and will know how to import it and serve your FastAPI app. 😎
## Deployment Concepts
## Deployment Concepts { #deployment-concepts }
Let's talk again about some of the same [Deployment Concepts](concepts.md){.internal-link target=_blank} in terms of containers.
@ -430,7 +430,7 @@ Let's review these **deployment concepts** in terms of containers:
* Memory
* Previous steps before starting
## HTTPS
## HTTPS { #https }
If we focus just on the **container image** for a FastAPI application (and later the running **container**), HTTPS normally would be handled **externally** by another tool.
@ -444,7 +444,7 @@ Traefik has integrations with Docker, Kubernetes, and others, so it's very easy
Alternatively, HTTPS could be handled by a cloud provider as one of their services (while still running the application in a container).
## Running on Startup and Restarts
## Running on Startup and Restarts { #running-on-startup-and-restarts }
There is normally another tool in charge of **starting and running** your container.
@ -454,7 +454,7 @@ In most (or all) cases, there's a simple option to enable running the container
Without using containers, making applications run on startup and with restarts can be cumbersome and difficult. But when **working with containers** in most cases that functionality is included by default. ✨
## Replication - Number of Processes
## Replication - Number of Processes { #replication-number-of-processes }
If you have a <abbrtitle="A group of machines that are configured to be connected and work together in some way.">cluster</abbr> of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container.
@ -462,7 +462,7 @@ One of those distributed container management systems like Kubernetes normally h
In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of using multiple Uvicorn workers.
### Load Balancer
### Load Balancer { #load-balancer }
When using containers, you would normally have some component **listening on the main port**. It could possibly be another container that is also a **TLS Termination Proxy** to handle **HTTPS** or some similar tool.
@ -476,7 +476,7 @@ The same **TLS Termination Proxy** component used for HTTPS would probably also
And when working with containers, the same system you use to start and manage them would already have internal tools to transmit the **network communication** (e.g. HTTP requests) from that **load balancer** (that could also be a **TLS Termination Proxy**) to the container(s) with your app.
### One Load Balancer - Multiple Worker Containers
When working with **Kubernetes** or similar distributed container management systems, using their internal networking mechanisms would allow the single **load balancer** that is listening on the main **port** to transmit communication (requests) to possibly **multiple containers** running your app.
@ -486,7 +486,7 @@ And the distributed container system with the **load balancer** would **distribu
And normally this **load balancer** would be able to handle requests that go to *other* apps in your cluster (e.g. to a different domain, or under a different URL path prefix), and would transmit that communication to the right containers for *that other* application running in your cluster.
### One Process per Container
### One Process per Container { #one-process-per-container }
In this type of scenario, you probably would want to have **a single (Uvicorn) process per container**, as you would already be handling replication at the cluster level.
@ -494,7 +494,7 @@ So, in this case, you **would not** want to have a multiple workers in the conta
Having another process manager inside the container (as would be with multiple workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system.
### Containers with Multiple Processes and Special Cases
### Containers with Multiple Processes and Special Cases { #containers-with-multiple-processes-and-special-cases }
Of course, there are **special cases** where you could want to have **a container** with several **Uvicorn worker processes** inside.
Here are some examples of when that could make sense:
#### A Simple App
#### A Simple App { #a-simple-app }
You could want a process manager in the container if your application is **simple enough** that can run it on a **single server**, not a cluster.
#### Docker Compose
#### Docker Compose { #docker-compose }
You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**.
@ -540,7 +540,7 @@ The main point is, **none** of these are **rules written in stone** that you hav
* Memory
* Previous steps before starting
## Memory
## Memory { #memory }
If you run **a single process per container** you will have a more or less well-defined, stable, and limited amount of memory consumed by each of those containers (more than one if they are replicated).
@ -550,11 +550,11 @@ If your application is **simple**, this will probably **not be a problem**, and
If you run **multiple processes per container** you will have to make sure that the number of processes started doesn't **consume more memory** than what is available.
## Previous Steps Before Starting and Containers
## Previous Steps Before Starting and Containers { #previous-steps-before-starting-and-containers }
If you are using containers (e.g. Docker, Kubernetes), then there are two main approaches you can use.
### Multiple Containers
### Multiple Containers { #multiple-containers }
If you have **multiple containers**, probably each one running a **single process** (for example, in a **Kubernetes** cluster), then you would probably want to have a **separate container** doing the work of the **previous steps** in a single container, running a single process, **before** running the replicated worker containers.
@ -566,11 +566,11 @@ If you are using Kubernetes, this would probably be an <a href="https://kubernet
If in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process.
### Single Container
### Single Container { #single-container }
If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app.
### Base Docker Image
### Base Docker Image { #base-docker-image }
There used to be an official FastAPI Docker image: <ahref="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker"class="external-link"target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>. But it is now deprecated. ⛔️
@ -588,7 +588,7 @@ But now that Uvicorn (and the `fastapi` command) support using `--workers`, ther
///
## Deploy the Container Image
## Deploy the Container Image { #deploy-the-container-image }
After having a Container (Docker) Image there are several ways to deploy it.
@ -600,11 +600,11 @@ For example:
* With another tool like Nomad
* With a cloud service that takes your container image and deploys it
## Docker Image with `uv`
## Docker Image with `uv` { #docker-image-with-uv }
If you are using <ahref="https://github.com/astral-sh/uv"class="external-link"target="_blank">uv</a> to install and manage your project, you can follow their <ahref="https://docs.astral.sh/uv/guides/integration/docker/"class="external-link"target="_blank">uv Docker guide</a>.
## Recap
## Recap { #recap }
Using container systems (e.g. with **Docker** and **Kubernetes**) it becomes fairly straightforward to handle all the **deployment concepts**:
It is easy to assume that HTTPS is something that is just "enabled" or not.
@ -43,7 +43,7 @@ Some of the options you could use as a TLS Termination Proxy are:
* Nginx
* HAProxy
## Let's Encrypt
## Let's Encrypt { #lets-encrypt }
Before Let's Encrypt, these **HTTPS certificates** were sold by trusted third parties.
@ -57,11 +57,11 @@ The domains are securely verified and the certificates are generated automatical
The idea is to automate the acquisition and renewal of these certificates so that you can have **secure HTTPS, for free, forever**.
## HTTPS for Developers
## HTTPS for Developers { #https-for-developers }
Here's an example of how an HTTPS API could look like, step by step, paying attention mainly to the ideas important for developers.
### Domain Name
### Domain Name { #domain-name }
It would probably all start by you **acquiring** some **domain name**. Then, you would configure it in a DNS server (possibly your same cloud provider).
@ -77,7 +77,7 @@ This Domain Name part is way before HTTPS, but as everything depends on the doma
///
### DNS
### DNS { #dns }
Now let's focus on all the actual HTTPS parts.
@ -85,19 +85,19 @@ First, the browser would check with the **DNS servers** what is the **IP for the
The DNS servers would tell the browser to use some specific **IP address**. That would be the public IP address used by your server, that you configured in the DNS servers.
The browser would then communicate with that IP address on **port 443** (the HTTPS port).
The first part of the communication is just to establish the connection between the client and the server and to decide the cryptographic keys they will use, etc.
This interaction between the client and the server to establish the TLS connection is called the **TLS handshake**.
### TLS with SNI Extension
### TLS with SNI Extension { #tls-with-sni-extension }
**Only one process** in the server can be listening on a specific **port** in a specific **IP address**. There could be other processes listening on other ports in the same IP address, but only one for each combination of IP address and port.
@ -111,7 +111,7 @@ Using the **SNI extension** discussed above, the TLS Termination Proxy would che
In this case, it would use the certificate for `someapp.example.com`.
The client already **trusts** the entity that generated that TLS certificate (in this case Let's Encrypt, but we'll see about that later), so it can **verify** that the certificate is valid.
@ -127,53 +127,53 @@ Notice that the encryption of the communication happens at the **TCP level**, no
///
### HTTPS Request
### HTTPS Request { #https-request }
Now that the client and server (specifically the browser and the TLS Termination Proxy) have an **encrypted TCP connection**, they can start the **HTTP communication**.
So, the client sends an **HTTPS request**. This is just an HTTP request through an encrypted TLS connection.
The TLS Termination Proxy would use the encryption agreed to **decrypt the request**, and would transmit the **plain (decrypted) HTTP request** to the process running the application (for example a process with Uvicorn running the FastAPI application).
The TLS Termination Proxy would then **encrypt the response** using the cryptography agreed before (that started with the certificate for `someapp.example.com`), and send it back to the browser.
Next, the browser would verify that the response is valid and encrypted with the right cryptographic key, etc. It would then **decrypt the response** and process it.
The client (browser) will know that the response comes from the correct server because it is using the cryptography they agreed using the **HTTPS certificate** before.
In the same server (or servers), there could be **multiple applications**, for example, other API programs or a database.
Only one process can be handling the specific IP and port (the TLS Termination Proxy in our example) but the other applications/processes can be running on the server(s) too, as long as they don't try to use the same **combination of public IP and port**.
That way, the TLS Termination Proxy could handle HTTPS and certificates for **multiple domains**, for multiple applications, and then transmit the requests to the right application in each case.
### Certificate Renewal
### Certificate Renewal { #certificate-renewal }
At some point in the future, each certificate would **expire** (about 3 months after acquiring it).
And then, there would be another program (in some cases it's another program, in some cases it could be the same TLS Termination Proxy) that would talk to Let's Encrypt, and renew the certificate(s).
<imgsrc="/img/deployment/https/https.svg">
<imgsrc="/img/deployment/https/https.drawio.svg">
The **TLS certificates** are **associated with a domain name**, not with an IP address.
@ -190,7 +190,39 @@ To do that, and to accommodate different application needs, there are several wa
All this renewal process, while still serving the app, is one of the main reasons why you would want to have a **separate system to handle HTTPS** with a TLS Termination Proxy instead of just using the TLS certificates with the application server directly (e.g. Uvicorn).
When using a proxy to handle HTTPS, your **application server** (for example Uvicorn via FastAPI CLI) doesn't known anything about the HTTPS process, it communicates with plain HTTP with the **TLS Termination Proxy**.
This **proxy** would normally set some HTTP headers on the fly before transmitting the request to the **application server**, to let the application server know that the request is being **forwarded** by the proxy.
Nevertheless, as the **application server** doesn't know it is behind a trusted **proxy**, by default, it wouldn't trust those headers.
But you can configure the **application server** to trust the *forwarded* headers sent by the **proxy**. If you are using FastAPI CLI, you can use the *CLI Option*`--forwarded-allow-ips` to tell it from which IPs it should trust those *forwarded* headers.
For example, if the **application server** is only receiving communication from the trusted **proxy**, you can set it to `--forwarded-allow-ips="*"` to make it trust all incoming IPs, as it will only receive requests from whatever is the IP used by the **proxy**.
This way the application would be able to know what is its own public URL, if it is using HTTPS, the domain, etc.
This would be useful for example to properly handle redirects.
/// tip
You can learn more about this in the documentation for [Behind a Proxy - Enable Proxy Forwarded Headers](../advanced/behind-a-proxy.md#enable-proxy-forwarded-headers){.internal-link target=_blank}
///
## Recap { #recap }
Having **HTTPS** is very important, and quite **critical** in most cases. Most of the effort you as a developer have to put around HTTPS is just about **understanding these concepts** and how they work.
Deploying a **FastAPI** application is relatively easy.
## What Does Deployment Mean
## What Does Deployment Mean { #what-does-deployment-mean }
To **deploy** an application means to perform the necessary steps to make it **available to the users**.
@ -10,7 +10,7 @@ For a **web API**, it normally involves putting it in a **remote machine**, with
This is in contrast to the **development** stages, where you are constantly changing the code, breaking it and fixing it, stopping and restarting the development server, etc.
# Run a Server Manually { #run-a-server-manually }
## Use the `fastapi run` Command
## Use the `fastapi run` Command { #use-the-fastapi-run-command }
In short, use `fastapi run` to serve your FastAPI application:
@ -42,7 +42,7 @@ That would work for most of the cases. 😎
You could use that command for example to start your **FastAPI** app in a container, in a server, etc.
## ASGI Servers
## ASGI Servers { #asgi-servers }
Let's go a little deeper into the details.
@ -58,7 +58,7 @@ There are several alternatives, including:
* <ahref="https://github.com/emmett-framework/granian"class="external-link"target="_blank">Granian</a>: A Rust HTTP server for Python applications.
* <ahref="https://unit.nginx.org/howto/fastapi/"class="external-link"target="_blank">NGINX Unit</a>: NGINX Unit is a lightweight and versatile web application runtime.
## Server Machine and Server Program
## Server Machine and Server Program { #server-machine-and-server-program }
There's a small detail about names to keep in mind. 💡
@ -68,7 +68,7 @@ Just keep in mind that when you read "server" in general, it could refer to one
When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs.
## Install the Server Program
## Install the Server Program { #install-the-server-program }
When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command.
@ -100,7 +100,7 @@ When you install FastAPI with something like `pip install "fastapi[standard]"` y
///
## Run the Server Program
## Run the Server Program { #run-the-server-program }
If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application:
@ -141,7 +141,7 @@ It helps a lot during **development**, but you **shouldn't** use it in **product
///
## Deployment Concepts
## Deployment Concepts { #deployment-concepts }
These examples run the server program (e.g Uvicorn), starting **a single process**, listening on all the IPs (`0.0.0.0`) on a predefined port (e.g. `80`).
# Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers }
Let's check back those deployment concepts from before:
@ -25,7 +25,7 @@ In particular, when running on **Kubernetes** you will probably **not** want to
///
## Multiple Workers
## Multiple Workers { #multiple-workers }
You can start multiple workers with the `--workers` command line option:
@ -111,7 +111,7 @@ The only new option here is `--workers` telling Uvicorn to start 4 worker proces
You can also see that it shows the **PID** of each process, `27365` for the parent process (this is the **process manager**) and one for each worker process: `27368`, `27369`, `27370`, and `27367`.
## Deployment Concepts
## Deployment Concepts { #deployment-concepts }
Here you saw how to use multiple **workers** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**.
@ -124,13 +124,13 @@ From the list of deployment concepts from above, using workers would mainly help
* **Memory**
* **Previous steps before starting**
## Containers and Docker
## Containers and Docker { #containers-and-docker }
In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll explain some strategies you could use to handle the other **deployment concepts**.
I'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**.
## Recap
## Recap { #recap }
You can use multiple worker processes with the `--workers` CLI option with the `fastapi` or `uvicorn` commands to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**.
# About FastAPI versions { #about-fastapi-versions }
**FastAPI** is already being used in production in many applications and systems. And the test coverage is kept at 100%. But its development is still moving quickly.
@ -8,7 +8,7 @@ That's why the current versions are still `0.x.x`, this reflects that each versi
You can create production applications with **FastAPI** right now (and you have probably been doing it for some time), you just have to make sure that you use a version that works correctly with the rest of your code.
## Pin your `fastapi` version
## Pin your `fastapi` version { #pin-your-fastapi-version }
The first thing you should do is to "pin" the version of **FastAPI** you are using to the specific latest version that you know works correctly for your application.
@ -32,11 +32,11 @@ that would mean that you would use the versions `0.112.0` or above, but less tha
If you use any other tool to manage your installations, like `uv`, Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages.
## Available versions
## Available versions { #available-versions }
You can see the available versions (e.g. to check what is the current latest) in the [Release Notes](../release-notes.md){.internal-link target=_blank}.
## About versions
## About versions { #about-versions }
Following the Semantic Versioning conventions, any version below `1.0.0` could potentially add breaking changes.
@ -62,7 +62,7 @@ The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR vers
///
## Upgrading the FastAPI versions
## Upgrading the FastAPI versions { #upgrading-the-fastapi-versions }
You should add tests for your app.
@ -72,7 +72,7 @@ After you have tests, then you can upgrade the **FastAPI** version to a more rec
If everything is working, or after you make the necessary changes, and all your tests are passing, then you can pin your `fastapi` to that new recent version.
## About Starlette
## About Starlette { #about-starlette }
You shouldn't pin the version of `starlette`.
@ -80,7 +80,7 @@ Different versions of **FastAPI** will use a specific newer version of Starlette
So, you can just let **FastAPI** use the correct Starlette version.
## About Pydantic
## About Pydantic { #about-pydantic }
Pydantic includes the tests for **FastAPI** with its own tests, so new versions of Pydantic (above `1.0.0`) are always compatible with FastAPI.
@ -10,7 +10,7 @@ An environment variable (also known as "**env var**") is a variable that lives *
Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc.
## Create and Use Env Vars
## Create and Use Env Vars { #create-and-use-env-vars }
You can **create** and use environment variables in the **shell (terminal)**, without needing Python:
@ -50,7 +50,7 @@ Hello Wade Wilson
////
## Read env vars in Python
## Read env vars in Python { #read-env-vars-in-python }
You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**.
@ -157,7 +157,7 @@ You can read more about it at <a href="https://12factor.net/config" class="exter
///
## Types and Validation
## Types and Validation { #types-and-validation }
These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS).
@ -165,7 +165,7 @@ That means that **any value** read in Python from an environment variable **will
You will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}.
By default, **auto-reload** is enabled, automatically reloading the server when you make changes to your code. This is resource-intensive and could be less stable than when it's disabled. You should only use it for development. It also listens on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`).
## `fastapi run`
## `fastapi run` { #fastapi-run }
Executing `fastapi run` starts FastAPI in production mode by default.
### Based on open standards { #based-on-open-standards }
* <ahref="https://github.com/OAI/OpenAPI-Specification"class="external-link"target="_blank"><strong>OpenAPI</strong></a> for API creation, including declarations of <abbrtitle="also known as: endpoints, routes">path</abbr><abbrtitle="also known as HTTP methods, as POST, GET, PUT, DELETE">operations</abbr>, parameters, request bodies, security, etc.
* Automatic data model documentation with <ahref="https://json-schema.org/"class="external-link"target="_blank"><strong>JSON Schema</strong></a> (as OpenAPI itself is based on JSON Schema).
* Designed around these standards, after a meticulous study. Instead of an afterthought layer on top.
* This also allows using automatic **client code generation** in many languages.
### Automatic docs
### Automatic docs { #automatic-docs }
Interactive API documentation and exploration web user interfaces. As the framework is based on OpenAPI, there are multiple options, 2 included by default.
@ -23,7 +23,7 @@ Interactive API documentation and exploration web user interfaces. As the framew
It's all based on standard **Python type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python.
@ -71,7 +71,7 @@ Pass the keys and values of the `second_user_data` dict directly as key-value ar
///
### Editor support
### Editor support { #editor-support }
All the framework was designed to be easy and intuitive to use, all the decisions were tested on multiple editors even before starting development, to ensure the best development experience.
@ -95,13 +95,13 @@ You will get completion in code you might even consider impossible before. As fo
No more typing the wrong key names, coming back and forth between docs, or scrolling up and down to find if you finally used `username` or `user_name`.
### Short
### Short { #short }
It has sensible **defaults** for everything, with optional configurations everywhere. All the parameters can be fine-tuned to do what you need and to define the API you need.
But by default, it all **"just works"**.
### Validation
### Validation { #validation }
* Validation for most (or all?) Python **data types**, including:
* JSON objects (`dict`).
@ -117,7 +117,7 @@ But by default, it all **"just works"**.
All the validation is handled by the well-established and robust **Pydantic**.
### Security and authentication
### Security and authentication { #security-and-authentication }
Security and authentication integrated. Without any compromise with databases or data models.
@ -134,7 +134,7 @@ Plus all the security features from Starlette (including **session cookies**).
All built as reusable tools and components that are easy to integrate with your systems, data stores, relational and NoSQL databases, etc.
FastAPI includes an extremely easy to use, but extremely powerful <abbrtitle='also known as "components", "resources", "services", "providers"'><strong>Dependency Injection</strong></abbr> system.
@ -145,19 +145,19 @@ FastAPI includes an extremely easy to use, but extremely powerful <abbr title='a
* Support for complex user authentication systems, **database connections**, etc.
* **No compromise** with databases, frontends, etc. But easy integration with all of them.
### Unlimited "plug-ins"
### Unlimited "plug-ins" { #unlimited-plug-ins }
Or in other way, no need for them, import and use the code you need.
Any integration is designed to be so simple to use (with dependencies) that you can create a "plug-in" for your application in 2 lines of code using the same structure and syntax used for your *path operations*.
### Tested
### Tested { #tested }
* 100% <abbrtitle="The amount of code that is automatically tested">test coverage</abbr>.
* 100% <abbrtitle="Python type annotations, with this your editor and external tools can give you better support">type annotated</abbr> code base.
* Used in production applications.
## Starlette features
## Starlette features { #starlette-features }
**FastAPI** is fully compatible with (and based on) <ahref="https://www.starlette.io/"class="external-link"target="_blank"><strong>Starlette</strong></a>. So, any additional Starlette code you have, will also work.
@ -175,7 +175,7 @@ With **FastAPI** you get all of **Starlette**'s features (as FastAPI is just Sta
* 100% test coverage.
* 100% type annotated codebase.
## Pydantic features
## Pydantic features { #pydantic-features }
**FastAPI** is fully compatible with (and based on) <ahref="https://docs.pydantic.dev/"class="external-link"target="_blank"><strong>Pydantic</strong></a>. So, any additional Pydantic code you have, will also work.
Some files were not shown because too many files changed in this diff