mirror of
https://github.com/fastapi/fastapi.git
synced 2026-06-19 21:08:47 -04:00
Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
041cb0cdfa | ||
|
|
10393846ed | ||
|
|
0303491b69 | ||
|
|
190f6e2033 | ||
|
|
17945e5ab7 | ||
|
|
2260afaf43 | ||
|
|
0cd5001d0e | ||
|
|
7cb1ab6264 | ||
|
|
9c7eceb00f | ||
|
|
d176e00b9f | ||
|
|
71e608e00e | ||
|
|
459a51097b | ||
|
|
e12833aaa2 | ||
|
|
4d3dc78b26 | ||
|
|
f1d750fdda | ||
|
|
22f99d9ad3 | ||
|
|
2d00470875 | ||
|
|
6e6c74fc16 | ||
|
|
1b68e378ef | ||
|
|
da9d05bc7a | ||
|
|
c61384e3d7 | ||
|
|
08321394ab | ||
|
|
c744991f96 | ||
|
|
2f4ba0bdd1 |
3
.github/workflows/test.yml
vendored
3
.github/workflows/test.yml
vendored
@@ -245,9 +245,10 @@ jobs:
|
||||
- run: uv run coverage report --fail-under=100
|
||||
|
||||
# https://github.com/marketplace/actions/alls-green#why
|
||||
check: # This job does nothing and is only used for the branch protection
|
||||
test-alls-green: # This job does nothing and is only used for the branch protection
|
||||
if: always()
|
||||
needs:
|
||||
- test
|
||||
- coverage-combine
|
||||
- benchmark
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -432,13 +432,13 @@ For a more complete example including more features, see the <a href="https://fa
|
||||
|
||||
**Spoiler alert**: the tutorial - user guide includes:
|
||||
|
||||
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
|
||||
* How to set **validation constraints** as `maximum_length` or `regex`.
|
||||
* Declaration of **parameters** from other different places such as: **headers**, **cookies**, **form fields** and **files**.
|
||||
* How to set **validation constraints** such as `maximum_length` or `regex`.
|
||||
* A very powerful and easy to use **<dfn title="also known as components, resources, providers, services, injectables">Dependency Injection</dfn>** system.
|
||||
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
|
||||
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
|
||||
* **GraphQL** integration with [Strawberry](https://strawberry.rocks) and other libraries.
|
||||
* Many extra features (thanks to Starlette) as:
|
||||
* Many extra features (thanks to Starlette) such as:
|
||||
* **WebSockets**
|
||||
* extremely easy tests based on HTTPX and `pytest`
|
||||
* **CORS**
|
||||
|
||||
@@ -185,7 +185,7 @@ See section `### Links` in the general prompt in `scripts/translate.py`.
|
||||
|
||||
//// tab | Test
|
||||
|
||||
Here some things wrapped in HTML "abbr" elements (Some are invented):
|
||||
Here are some things wrapped in HTML "abbr" elements (Some are invented):
|
||||
|
||||
### The abbr gives a full phrase { #the-abbr-gives-a-full-phrase }
|
||||
|
||||
@@ -488,7 +488,7 @@ For some language specific instructions, see e.g. section `### Headings` in `doc
|
||||
|
||||
//// tab | Info
|
||||
|
||||
This is a not complete and not normative list of (mostly) technical terms seen in the docs. It may be helpful for the prompt designer to figure out for which terms the LLM needs a helping hand. For example when it keeps reverting a good translation to a suboptimal translation. Or when it has problems conjugating/declinating a term in your language.
|
||||
This is neither a complete nor a normative list of (mostly) technical terms seen in the docs. It may be helpful for the prompt designer to figure out for which terms the LLM needs a helping hand. For example when it keeps reverting a good translation to a suboptimal translation. Or when it has problems conjugating/declinating a term in your language.
|
||||
|
||||
See e.g. section `### List of English terms and their preferred German translations` in `docs/de/llm-prompt.md`.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ It will use the default status code or the one you set in your *path operation*.
|
||||
|
||||
If you want to return additional status codes apart from the main one, you can do that by returning a `Response` directly, like a `JSONResponse`, and set the additional status code directly.
|
||||
|
||||
For example, let's say that you want to have a *path operation* that allows to update items, and returns HTTP status codes of 200 "OK" when successful.
|
||||
For example, let's say that you want to have a *path operation* that allows updating items, and returns HTTP status codes of 200 "OK" when successful.
|
||||
|
||||
But you also want it to accept new items. And when the items didn't exist before, it creates them, and returns an HTTP status code of 201 "Created".
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ checker(q="somequery")
|
||||
|
||||
/// tip
|
||||
|
||||
All this might seem contrived. And it might not be very clear how is it useful yet.
|
||||
All this might seem contrived. And it might not be very clear how it is useful yet.
|
||||
|
||||
These examples are intentionally simple, but show how it all works.
|
||||
|
||||
@@ -112,7 +112,7 @@ For example, imagine you have code that uses a database session in a dependency
|
||||
|
||||
In this case, the database session would be held until the response is finished being sent, but if you don't use it, then it wouldn't be necessary to hold it.
|
||||
|
||||
Here's how it could look like:
|
||||
Here's how it could look:
|
||||
|
||||
{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Keep in mind that dataclasses can't do everything Pydantic models can do.
|
||||
|
||||
So, you might still need to use Pydantic models.
|
||||
|
||||
But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
|
||||
But if you have a bunch of dataclasses lying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
|
||||
|
||||
///
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@ So, we declare the event handler function with standard `def` instead of `async
|
||||
|
||||
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.
|
||||
|
||||
Doing that in separated functions that don't share logic or variables together is more difficult as you would need to store values in global variables or similar tricks.
|
||||
Doing that in separate functions that don't share logic or variables together is more difficult as you would need to store values in global variables or similar tricks.
|
||||
|
||||
Because of that, it's now recommended to instead use the `lifespan` as explained above.
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ FastAPI automatically generates **OpenAPI 3.1** specifications, so any tool you
|
||||
|
||||
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.
|
||||
|
||||
By ✨ [**sponsoring FastAPI**](../help-fastapi.md#sponsor-the-author) ✨, these companies help ensure the framework and its **ecosystem** remain healthy and **sustainable**.
|
||||
By ✨ [**sponsoring FastAPI**](https://github.com/sponsors/tiangolo) ✨, these companies help ensure the framework and its **ecosystem** remain healthy and **sustainable**.
|
||||
|
||||
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. 🙇
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ If your app needs to receive and send JSON data, but you need to include binary
|
||||
|
||||
## Base64 vs Files { #base64-vs-files }
|
||||
|
||||
Consider first if you can use [Request Files](../tutorial/request-files.md) for uploading binary data and [Custom Response - FileResponse](./custom-response.md#fileresponse--fileresponse-) for sending binary data, instead of encoding it in JSON.
|
||||
Consider first if you can use [Request Files](../tutorial/request-files.md) for uploading binary data and [Custom Response - FileResponse](./custom-response.md#fileresponse) for sending binary data, instead of encoding it in JSON.
|
||||
|
||||
JSON can only contain UTF-8 encoded strings, so it can't contain raw bytes.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ You could create an API with a *path operation* that could trigger a request to
|
||||
|
||||
The process that happens when your API app calls the *external API* is named a "callback". Because the software that the external developer wrote sends a request to your API and then your API *calls back*, sending a request to an *external API* (that was probably created by the same developer).
|
||||
|
||||
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.
|
||||
In this case, you could want to document how that external API *should* look. 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 }
|
||||
|
||||
@@ -25,7 +25,7 @@ Then your API will (let's imagine):
|
||||
|
||||
## The normal **FastAPI** app { #the-normal-fastapi-app }
|
||||
|
||||
Let's first see how the normal API app would look like before adding the callback.
|
||||
Let's first see how the normal API app would look before adding the callback.
|
||||
|
||||
It will have a *path operation* that will receive an `Invoice` body, and a query parameter `callback_url` that will contain the URL for the callback.
|
||||
|
||||
@@ -56,7 +56,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
|
||||
|
||||
But possibly the most important part of the callback is making sure that your API user (the external developer) implements the *external API* correctly, according to the data that *your API* is going to send in the request body of the callback, etc.
|
||||
|
||||
So, what we will do next is add the code to document how that *external API* should look like to receive the callback from *your API*.
|
||||
So, what we will do next is add the code to document how that *external API* should look to receive the callback from *your API*.
|
||||
|
||||
That documentation will show up in the Swagger UI at `/docs` in your API, and it will let external developers know how to build the *external API*.
|
||||
|
||||
@@ -72,11 +72,11 @@ When implementing the callback yourself, you could use something like [HTTPX](ht
|
||||
|
||||
## 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.
|
||||
This code won't be executed in your app, we only need it to *document* how that *external API* should look.
|
||||
|
||||
But, you already know how to easily create automatic documentation for an API with **FastAPI**.
|
||||
|
||||
So we are going to use that same knowledge to document how the *external API* should look like... by creating the *path operation(s)* that the external API should implement (the ones your API will call).
|
||||
So we are going to use that same knowledge to document how the *external API* should look... by creating the *path operation(s)* that the external API should implement (the ones your API will call).
|
||||
|
||||
/// tip
|
||||
|
||||
@@ -181,6 +181,6 @@ Notice that you are not passing the router itself (`invoices_callback_router`) t
|
||||
|
||||
Now you can start your app and go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
|
||||
|
||||
You will see your docs including a "Callbacks" section for your *path operation* that shows how the *external API* should look like:
|
||||
You will see your docs including a "Callbacks" section for your *path operation* that shows how the *external API* should look:
|
||||
|
||||
<img src="/img/tutorial/openapi-callbacks/image01.png">
|
||||
|
||||
@@ -18,7 +18,7 @@ For those cases, you can use a `Response` parameter.
|
||||
|
||||
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies and headers).
|
||||
|
||||
And then you can set the `status_code` in that *temporal* response object.
|
||||
And then you can set the `status_code` in that *temporary* response object.
|
||||
|
||||
{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
|
||||
|
||||
@@ -26,6 +26,6 @@ And then you can return any object you need, as you normally would (a `dict`, a
|
||||
|
||||
And if you declared a `response_model`, it will still be used to filter and convert the object you returned.
|
||||
|
||||
**FastAPI** will use that *temporal* response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
|
||||
**FastAPI** will use that *temporary* response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
|
||||
|
||||
You can also declare the `Response` parameter in dependencies, and set the status code in them. But keep in mind that the last one to be set will win.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
You can declare a parameter of type `Response` in your *path operation function*.
|
||||
|
||||
And then you can set cookies in that *temporal* response object.
|
||||
And then you can set cookies in that *temporary* response object.
|
||||
|
||||
{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
|
||||
|
||||
@@ -12,7 +12,7 @@ And then you can return any object you need, as you normally would (a `dict`, a
|
||||
|
||||
And if you declared a `response_model`, it will still be used to filter and convert the object you returned.
|
||||
|
||||
**FastAPI** will use that *temporal* response to extract the cookies (also headers and status code), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
|
||||
**FastAPI** will use that *temporary* response to extract the cookies (also headers and status code), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
|
||||
|
||||
You can also declare the `Response` parameter in dependencies, and set cookies (and headers) in them.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies).
|
||||
|
||||
And then you can set headers in that *temporal* response object.
|
||||
And then you can set headers in that *temporary* response object.
|
||||
|
||||
{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
|
||||
|
||||
@@ -12,7 +12,7 @@ And then you can return any object you need, as you normally would (a `dict`, a
|
||||
|
||||
And if you declared a `response_model`, it will still be used to filter and convert the object you returned.
|
||||
|
||||
**FastAPI** will use that *temporal* response to extract the headers (also cookies and status code), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
|
||||
**FastAPI** will use that *temporary* response to extract the headers (also cookies and status code), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
|
||||
|
||||
You can also declare the `Response` parameter in dependencies, and set headers (and cookies) in them.
|
||||
|
||||
|
||||
@@ -194,11 +194,11 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these
|
||||
|
||||
Let's review again this dependency tree and the scopes.
|
||||
|
||||
As the `get_current_active_user` dependency has as a sub-dependency on `get_current_user`, the scope `"me"` declared at `get_current_active_user` will be included in the list of required scopes in the `security_scopes.scopes` passed to `get_current_user`.
|
||||
As the `get_current_active_user` dependency has `get_current_user` as a sub-dependency, the scope `"me"` declared at `get_current_active_user` will be included in the list of required scopes in the `security_scopes.scopes` passed to `get_current_user`.
|
||||
|
||||
The *path operation* itself also declares a scope, `"items"`, so this will also be in the list of `security_scopes.scopes` passed to `get_current_user`.
|
||||
|
||||
Here's how the hierarchy of dependencies and scopes looks like:
|
||||
Here's what the hierarchy of dependencies and scopes looks like:
|
||||
|
||||
* The *path operation* `read_own_items` has:
|
||||
* Required scopes `["items"]` with the dependency:
|
||||
|
||||
@@ -14,7 +14,7 @@ To understand environment variables you can read [Environment Variables](../envi
|
||||
|
||||
## 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).
|
||||
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, such as Linux, Windows, and 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.
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Added in FastAPI 0.134.0.
|
||||
|
||||
You could use this if you want to stream pure strings, for example directly from the output of an **AI LLM** service.
|
||||
|
||||
You could also use it to stream **large binary files**, where you stream each chunk of data as you read it, without having to read it all in memory at once.
|
||||
You could also use it to stream **large binary files**, where you stream each chunk of data as you read it, without having to read it all into memory at once.
|
||||
|
||||
You could also stream **video** or **audio** this way, it could even be generated as you process and send it.
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ And then mount that under a path.
|
||||
|
||||
Previously, it was recommended to use `WSGIMiddleware` from `fastapi.middleware.wsgi`, but it is now deprecated.
|
||||
|
||||
It’s advised to use the `a2wsgi` package instead. The usage remains the same.
|
||||
It's advised to use the `a2wsgi` package instead. The usage remains the same.
|
||||
|
||||
Just ensure that you have the `a2wsgi` package installed and import `WSGIMiddleware` correctly from `a2wsgi`.
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ It was created to generate the HTML in the backend, not to create APIs used by a
|
||||
|
||||
### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
|
||||
|
||||
Django REST framework was created to be a flexible toolkit for building Web APIs using Django underneath, to improve its API capabilities.
|
||||
Django REST Framework was created to be a flexible toolkit for building Web APIs using Django underneath, to improve its API capabilities.
|
||||
|
||||
It is used by many companies including Mozilla, Red Hat and Eventbrite.
|
||||
|
||||
@@ -345,7 +345,7 @@ Hug was created by Timothy Crosley, the same creator of [`isort`](https://github
|
||||
|
||||
Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.
|
||||
|
||||
Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
|
||||
Hug helped inspire **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
|
||||
|
||||
Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.
|
||||
|
||||
@@ -380,7 +380,7 @@ Now APIStar is a set of tools to validate OpenAPI specifications, not a web fram
|
||||
APIStar was created by Tom Christie. The same guy that created:
|
||||
|
||||
* Django REST Framework
|
||||
* Starlette (in which **FastAPI** is based)
|
||||
* Starlette (on which **FastAPI** is based)
|
||||
* Uvicorn (used by Starlette and **FastAPI**)
|
||||
|
||||
///
|
||||
@@ -393,7 +393,7 @@ The idea of declaring multiple things (data validation, serialization and docume
|
||||
|
||||
And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.
|
||||
|
||||
Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
|
||||
Then APIStar stopped existing as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
|
||||
|
||||
I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ Asynchronous code just means that the language 💬 has a way to tell the comput
|
||||
|
||||
So, during that time, the computer can go and do some other work, while "slow-file" 📝 finishes.
|
||||
|
||||
Then the computer / program 🤖 will come back every time it has a chance because it's waiting again, or whenever it 🤖 finished all the work it had at that point. And it 🤖 will see if any of the tasks it was waiting for have already finished, doing whatever it had to do.
|
||||
Then the computer / program 🤖 will come back every time it has a chance because it's waiting again, or whenever it 🤖 finishes all the work it had at that point. And it 🤖 will see if any of the tasks it was waiting for have already finished, doing whatever it had to do.
|
||||
|
||||
Next, it 🤖 takes the first task to finish (let's say, our "slow-file" 📝) and continues whatever it had to do with it.
|
||||
|
||||
@@ -78,7 +78,7 @@ That "wait for something else" normally refers to <abbr title="Input and Output"
|
||||
|
||||
* the data from the client to be sent through the network
|
||||
* the data sent by your program to be received by the client through the network
|
||||
* the contents of a file in the disk to be read by the system and given to your program
|
||||
* the contents of a file on the disk to be read by the system and given to your program
|
||||
* the contents your program gave to the system to be written to disk
|
||||
* a remote API operation
|
||||
* a database operation to finish
|
||||
@@ -257,7 +257,7 @@ And as you can have parallelism and asynchronicity at the same time, you get hig
|
||||
|
||||
Nope! That's not the moral of the story.
|
||||
|
||||
Concurrency is different than parallelism. And it is better on **specific** scenarios that involve a lot of waiting. Because of that, it generally is a lot better than parallelism for web application development. But not for everything.
|
||||
Concurrency is different than parallelism. And it is better in **specific** scenarios that involve a lot of waiting. Because of that, it generally is a lot better than parallelism for web application development. But not for everything.
|
||||
|
||||
So, to balance that out, imagine the following short story:
|
||||
|
||||
@@ -267,7 +267,7 @@ So, to balance that out, imagine the following short story:
|
||||
|
||||
---
|
||||
|
||||
There's no waiting 🕙 anywhere, just a lot of work to be done, on multiple places of the house.
|
||||
There's no waiting 🕙 anywhere, just a lot of work to be done, in multiple places of the house.
|
||||
|
||||
You could have turns as in the burgers example, first the living room, then the kitchen, but as you are not waiting 🕙 for anything, just cleaning and cleaning, the turns wouldn't affect anything.
|
||||
|
||||
@@ -296,7 +296,7 @@ With **FastAPI** you can take advantage of concurrency that is very common for w
|
||||
|
||||
But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems.
|
||||
|
||||
That, plus the simple fact that Python is the main language for **Data Science**, Machine Learning and especially Deep Learning, make FastAPI a very good match for Data Science / Machine Learning web APIs and applications (among many others).
|
||||
That, plus the simple fact that Python is the main language for **Data Science**, Machine Learning and especially Deep Learning, makes FastAPI a very good match for Data Science / Machine Learning web APIs and applications (among many others).
|
||||
|
||||
To see how to achieve this parallelism in production see the section about [Deployment](deployment/index.md).
|
||||
|
||||
@@ -340,7 +340,7 @@ burgers = get_burgers(2)
|
||||
|
||||
---
|
||||
|
||||
So, if you are using a library that tells you that you can call it with `await`, you need to create the *path operation functions* that uses it with `async def`, like in:
|
||||
So, if you are using a library that tells you that you can call it with `await`, you need to create the *path operation functions* that use it with `async def`, like in:
|
||||
|
||||
```Python hl_lines="2-3"
|
||||
@app.get('/burgers')
|
||||
@@ -435,7 +435,7 @@ Any other utility function that you call directly can be created with normal `de
|
||||
|
||||
This is in contrast to the functions that FastAPI calls for you: *path operation functions* and dependencies.
|
||||
|
||||
If your utility function is a normal function with `def`, it will be called directly (as you write it in your code), not in a threadpool, if the function is created with `async def` then you should `await` for that function when you call it in your code.
|
||||
If your utility function is a normal function with `def`, it will be called directly (as you write it in your code), not in a threadpool, if the function is created with `async def` then you should `await` that function when you call it in your code.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ FastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and f
|
||||
|
||||
## Cloud Providers - Sponsors { #cloud-providers-sponsors }
|
||||
|
||||
Some other cloud providers ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ too. 🙇
|
||||
Some other cloud providers ✨ [**sponsor FastAPI**](https://github.com/sponsors/tiangolo) ✨ too. 🙇
|
||||
|
||||
You might also want to consider them to follow their guides and try their services:
|
||||
|
||||
|
||||
@@ -36,9 +36,9 @@ And there has to be something in charge of **renewing the HTTPS certificates**,
|
||||
Some of the tools you could use as a TLS Termination Proxy are:
|
||||
|
||||
* Traefik
|
||||
* Automatically handles certificates renewals ✨
|
||||
* Automatically handles certificate renewals ✨
|
||||
* Caddy
|
||||
* Automatically handles certificates renewals ✨
|
||||
* Automatically handles certificate renewals ✨
|
||||
* Nginx
|
||||
* With an external component like Certbot for certificate renewals
|
||||
* HAProxy
|
||||
|
||||
@@ -283,7 +283,7 @@ CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"]
|
||||
|
||||
#### Docker Cache { #docker-cache }
|
||||
|
||||
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.
|
||||
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 that is.
|
||||
|
||||
```Dockerfile
|
||||
COPY ./requirements.txt /code/requirements.txt
|
||||
@@ -301,7 +301,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
|
||||
The file with the package requirements **won't change frequently**. So, by copying only that file, Docker will be able to **use the cache** for that step.
|
||||
|
||||
And then, Docker will be able to **use the cache for the next step** that downloads and install those dependencies. And here's where we **save a lot of time**. ✨ ...and avoid boredom waiting. 😪😆
|
||||
And then, Docker will be able to **use the cache for the next step** that downloads and installs those dependencies. And here's where we **save a lot of time**. ✨ ...and avoid boredom waiting. 😪😆
|
||||
|
||||
Downloading and installing the package dependencies **could take minutes**, but using the **cache** would **take seconds** at most.
|
||||
|
||||
@@ -488,7 +488,7 @@ And normally this **load balancer** would be able to handle requests that go to
|
||||
|
||||
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.
|
||||
|
||||
So, in this case, you **would not** want to have a multiple workers in the container, for example with the `--workers` command line option. You would want to have just a **single Uvicorn process** per container (but probably multiple containers).
|
||||
So, in this case, you **would not** want to have multiple workers in the container, for example with the `--workers` command line option. You would want to have just a **single Uvicorn process** per container (but probably multiple containers).
|
||||
|
||||
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.
|
||||
|
||||
@@ -519,7 +519,7 @@ Here are some examples of when that could make sense:
|
||||
|
||||
#### 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.
|
||||
You could want a process manager in the container if your application is **simple enough** that you can run it on a **single server**, not a cluster.
|
||||
|
||||
#### Docker Compose { #docker-compose }
|
||||
|
||||
@@ -544,7 +544,7 @@ If you run **a single process per container** you will have a more or less well-
|
||||
|
||||
And then you can set those same memory limits and requirements in your configurations for your container management system (for example in **Kubernetes**). That way it will be able to **replicate the containers** in the **available machines** taking into account the amount of memory needed by them, and the amount available in the machines in the cluster.
|
||||
|
||||
If your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that runs in **each machine** (and maybe add more machines to your cluster).
|
||||
If your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that run on **each machine** (and maybe add more machines to your cluster).
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ The idea is to automate the acquisition and renewal of these certificates so tha
|
||||
|
||||
## 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.
|
||||
Here's an example of how an HTTPS API could look, step by step, paying attention mainly to the ideas important for developers.
|
||||
|
||||
### Domain Name { #domain-name }
|
||||
|
||||
@@ -192,7 +192,7 @@ All this renewal process, while still serving the app, is one of the main reason
|
||||
|
||||
## Proxy Forwarded Headers { #proxy-forwarded-headers }
|
||||
|
||||
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**.
|
||||
When using a proxy to handle HTTPS, your **application server** (for example Uvicorn via FastAPI CLI) doesn't know 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.
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ A similar process would apply to any other ASGI server program.
|
||||
|
||||
By adding the `standard`, Uvicorn will install and use some recommended extra dependencies.
|
||||
|
||||
That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.
|
||||
That includes `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.
|
||||
|
||||
When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well.
|
||||
|
||||
|
||||
@@ -20,4 +20,4 @@ By default, the extension will automatically discover FastAPI applications in yo
|
||||
- **Deploy to FastAPI Cloud** - One-click deployment of your app to [FastAPI Cloud](https://fastapicloud.com/).
|
||||
- **Stream Application Logs** - Real-time log streaming from your FastAPI Cloud-deployed application with level filtering and text search.
|
||||
|
||||
If you'd like to familiarize yourself with the extension's features, you can checkout the extension walkthrough by opening the Command Palette (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> or on macOS: <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>) and selecting "Welcome: Open walkthrough..." and then choosing the "Get started with FastAPI" walkthrough.
|
||||
If you'd like to familiarize yourself with the extension's features, you can check out the extension walkthrough by opening the Command Palette (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> or on macOS: <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>) and selecting "Welcome: Open walkthrough..." and then choosing the "Get started with FastAPI" walkthrough.
|
||||
|
||||
@@ -159,7 +159,7 @@ You can read more about it at [The Twelve-Factor App: Config](https://12factor.n
|
||||
|
||||
## 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).
|
||||
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, such as Linux, Windows, and 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.
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ include_yaml:
|
||||
|
||||
**FastAPI** has a great community constantly growing.
|
||||
|
||||
There are many posts, articles, tools, and projects, related to **FastAPI**.
|
||||
There are many posts, articles, tools, and projects related to **FastAPI**.
|
||||
|
||||
You could easily use a search engine or video platform to find many resources related to FastAPI.
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ This is me:
|
||||
|
||||
</div>
|
||||
|
||||
I'm the creator of **FastAPI**. You can read more about that in [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author).
|
||||
I'm the creator of **FastAPI**. You can read more about that in [Help FastAPI - Follow the author](help-fastapi.md#follow-the-author).
|
||||
|
||||
...But here I want to show you the community.
|
||||
|
||||
@@ -42,9 +42,8 @@ I'm the creator of **FastAPI**. You can read more about that in [Help FastAPI -
|
||||
These are the people that:
|
||||
|
||||
* [Help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github).
|
||||
* [Create Pull Requests](help-fastapi.md#create-a-pull-request).
|
||||
* Review Pull Requests, [especially important for translations](contributing.md#translations).
|
||||
* Help [manage the repository](management-tasks.md) (team members).
|
||||
* Create or review Pull Requests.
|
||||
* Help [manage the repository](https://tiangolo.com/open-source/management-tasks/) (team members).
|
||||
|
||||
All these tasks help maintain the repository.
|
||||
|
||||
@@ -54,7 +53,7 @@ A round of applause to them. 👏 🙇
|
||||
|
||||
This is the current list of team members. 😎
|
||||
|
||||
They have different levels of involvement and permissions, they can perform [repository management tasks](./management-tasks.md) and together we [manage the FastAPI repository](./management.md).
|
||||
They have different levels of involvement and permissions, they can perform [repository management tasks](https://tiangolo.com/open-source/management-tasks/) and together we [manage the FastAPI repository](./management.md).
|
||||
|
||||
<div class="user-list user-list-center">
|
||||
|
||||
@@ -66,7 +65,7 @@ They have different levels of involvement and permissions, they can perform [rep
|
||||
|
||||
</div>
|
||||
|
||||
Although the team members have the permissions to perform privileged tasks, all the [help from others maintaining FastAPI](./help-fastapi.md#help-maintain-fastapi) is very much appreciated! 🙇♂️
|
||||
Although the team members have the permissions to perform privileged tasks, all the help from others maintaining FastAPI is very much appreciated! 🙇♂️
|
||||
|
||||
## FastAPI Experts
|
||||
|
||||
@@ -186,7 +185,7 @@ These are the users that have [helped others the most with questions in GitHub](
|
||||
|
||||
Here are the **Top Contributors**. 👷
|
||||
|
||||
These users have [created the most Pull Requests](help-fastapi.md#create-a-pull-request) that have been *merged*.
|
||||
These users have created the most Pull Requests that have been *merged*.
|
||||
|
||||
They have contributed source code, documentation, etc. 📦
|
||||
|
||||
@@ -210,7 +209,7 @@ There are hundreds of other contributors, you can see them all in the [FastAPI G
|
||||
|
||||
These users are the **Top Translation Reviewers**. 🕵️
|
||||
|
||||
Translation reviewers have the [**power to approve translations**](contributing.md#translations) of the documentation. Without them, there wouldn't be documentation in several other languages.
|
||||
Translation reviewers have the **power to approve translations** of the documentation. Without them, there wouldn't be documentation in several other languages.
|
||||
|
||||
<div class="user-list user-list-center">
|
||||
{% for user in (translation_reviewers.values() | list)[:50] %}
|
||||
|
||||
@@ -73,11 +73,11 @@ Pass the keys and values of the `second_user_data` dict directly as key-value ar
|
||||
|
||||
### 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.
|
||||
The whole 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.
|
||||
|
||||
In the Python developer surveys, it's clear [that one of the most used features is "autocompletion"](https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features).
|
||||
|
||||
The whole **FastAPI** framework is based to satisfy that. Autocompletion works everywhere.
|
||||
The whole **FastAPI** framework is designed to satisfy that. Autocompletion works everywhere.
|
||||
|
||||
You will rarely need to come back to the docs.
|
||||
|
||||
@@ -147,7 +147,7 @@ FastAPI includes an extremely easy to use, but extremely powerful <dfn title='al
|
||||
|
||||
### Unlimited "plug-ins" { #unlimited-plug-ins }
|
||||
|
||||
Or in other way, no need for them, import and use the code you need.
|
||||
Or, in other words, 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*.
|
||||
|
||||
@@ -179,7 +179,7 @@ With **FastAPI** you get all of **Starlette**'s features (as FastAPI is just Sta
|
||||
|
||||
**FastAPI** is fully compatible with (and based on) [**Pydantic**](https://docs.pydantic.dev/). So, any additional Pydantic code you have, will also work.
|
||||
|
||||
Including external libraries also based on Pydantic, as <abbr title="Object-Relational Mapper">ORM</abbr>s, <abbr title="Object-Document Mapper">ODM</abbr>s for databases.
|
||||
Including external libraries also based on Pydantic, such as <abbr title="Object-Relational Mapper">ORM</abbr>s and <abbr title="Object-Document Mapper">ODM</abbr>s for databases.
|
||||
|
||||
This also means that in many cases you can pass the same object you get from a request **directly to the database**, as everything is validated automatically.
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ You can follow **FastAPI** online in several places:
|
||||
|
||||
You can "star" FastAPI in GitHub (clicking the star button at the top right): [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi). ⭐️
|
||||
|
||||
By adding a star, other users will be able to find it more easily and see that it has been already useful for others.
|
||||
By adding a star, other users will be able to find it more easily and see that it has already been useful for others.
|
||||
|
||||
## Watch the GitHub repository for releases { #watch-the-github-repository-for-releases }
|
||||
|
||||
|
||||
@@ -67,4 +67,4 @@ presets: [
|
||||
|
||||
These are **JavaScript** objects, not strings, so you can't pass them from Python code directly.
|
||||
|
||||
If you need to use JavaScript-only configurations like those, you can use one of the methods above. Override all the Swagger UI *path operation* and manually write any JavaScript you need.
|
||||
If you need to use JavaScript-only configurations like those, you can use one of the methods above. Override the whole Swagger UI *path operation* and manually write any JavaScript you need.
|
||||
|
||||
@@ -94,7 +94,7 @@ All we need to do is handle the request inside a `try`/`except` block:
|
||||
|
||||
{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
|
||||
|
||||
If an exception occurs, the`Request` instance will still be in scope, so we can read and make use of the request body when handling the error:
|
||||
If an exception occurs, the `Request` instance will still be in scope, so we can read and make use of the request body when handling the error:
|
||||
|
||||
{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
|
||||
|
||||
|
||||
@@ -57,4 +57,4 @@ If you need GraphQL, I still would recommend you check out [Strawberry](https://
|
||||
|
||||
You can learn more about **GraphQL** in the [official GraphQL documentation](https://graphql.org/).
|
||||
|
||||
You can also read more about each those libraries described above in their links.
|
||||
You can also read more about each of those libraries described above in their links.
|
||||
|
||||
@@ -8,6 +8,8 @@ FastAPI version 0.119.0 introduced partial support for Pydantic v1 from inside o
|
||||
|
||||
FastAPI 0.126.0 dropped support for Pydantic v1, while still supporting `pydantic.v1` for a little while.
|
||||
|
||||
FastAPI 0.128.0 dropped support for `pydantic.v1` as well, so the latest versions of FastAPI require Pydantic v2.
|
||||
|
||||
/// warning
|
||||
|
||||
The Pydantic team stopped support for Pydantic v1 for the latest versions of Python, starting with **Python 3.14**.
|
||||
@@ -54,6 +56,16 @@ This means that you can install the latest version of Pydantic v2 and import and
|
||||
|
||||
### FastAPI support for Pydantic v1 in v2 { #fastapi-support-for-pydantic-v1-in-v2 }
|
||||
|
||||
/// warning
|
||||
|
||||
This FastAPI support for `pydantic.v1` models was added in **FastAPI 0.119.0** and removed in **FastAPI 0.128.0**. It was meant to be a temporary aid for the migration to Pydantic v2.
|
||||
|
||||
In current versions of FastAPI, using a `pydantic.v1` model in your app will raise an error.
|
||||
|
||||
The rest of this section describes the temporary support available only in those older versions.
|
||||
|
||||
///
|
||||
|
||||
Since FastAPI 0.119.0, there's also partial support for Pydantic v1 from inside of Pydantic v2, to facilitate the migration to v2.
|
||||
|
||||
So, you could upgrade Pydantic to the latest version 2, and change the imports to use the `pydantic.v1` submodule, and in many cases it would just work.
|
||||
@@ -88,7 +100,7 @@ graph TB
|
||||
style V2Field fill:#f9fff3
|
||||
```
|
||||
|
||||
...but, you can have separated models using Pydantic v1 and v2 in the same app.
|
||||
...but you can have separate models, some using Pydantic v1 and others using Pydantic v2, in the same app.
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
@@ -122,6 +134,12 @@ If you need to use some of the FastAPI-specific tools for parameters like `Body`
|
||||
|
||||
### Migrate in steps { #migrate-in-steps }
|
||||
|
||||
/// warning
|
||||
|
||||
The gradual migration using both Pydantic v1 and v2 models in the same app described below only works in **FastAPI 0.119.0 to 0.127.x**. It was removed in **FastAPI 0.128.0**, the latest versions require **Pydantic v2** models.
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
First try with `bump-pydantic`, if your tests pass and that works, then you're done in one command. ✨
|
||||
@@ -130,6 +148,6 @@ First try with `bump-pydantic`, if your tests pass and that works, then you're d
|
||||
|
||||
If `bump-pydantic` doesn't work for your use case, you can use the support for both Pydantic v1 and v2 models in the same app to do the migration to Pydantic v2 gradually.
|
||||
|
||||
You could fist upgrade Pydantic to use the latest version 2, and change the imports to use `pydantic.v1` for all your models.
|
||||
You could first upgrade Pydantic to use the latest version 2, and change the imports to use `pydantic.v1` for all your models.
|
||||
|
||||
Then, you can start migrating your models from Pydantic v1 to v2 in groups, in gradual steps. 🚶
|
||||
|
||||
@@ -46,7 +46,7 @@ If you interact with the docs and check the response, even though the code didn'
|
||||
|
||||
This means that it will **always have a value**, it's just that sometimes the value could be `None` (or `null` in JSON).
|
||||
|
||||
That means that, clients using your API don't have to check if the value exists or not, they can **assume the field will always be there**, but just that in some cases it will have the default value of `None`.
|
||||
That means that clients using your API don't have to check if the value exists or not, they can **assume the field will always be there**, but just that in some cases it will have the default value of `None`.
|
||||
|
||||
The way to describe this in OpenAPI, is to mark that field as **required**, because it will always be there.
|
||||
|
||||
|
||||
@@ -477,13 +477,13 @@ For a more complete example including more features, see the <a href="https://fa
|
||||
|
||||
**Spoiler alert**: the tutorial - user guide includes:
|
||||
|
||||
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
|
||||
* How to set **validation constraints** as `maximum_length` or `regex`.
|
||||
* Declaration of **parameters** from other different places such as: **headers**, **cookies**, **form fields** and **files**.
|
||||
* How to set **validation constraints** such as `maximum_length` or `regex`.
|
||||
* A very powerful and easy to use **<dfn title="also known as components, resources, providers, services, injectables">Dependency Injection</dfn>** system.
|
||||
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
|
||||
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
|
||||
* **GraphQL** integration with [Strawberry](https://strawberry.rocks) and other libraries.
|
||||
* Many extra features (thanks to Starlette) as:
|
||||
* Many extra features (thanks to Starlette) such as:
|
||||
* **WebSockets**
|
||||
* extremely easy tests based on HTTPX and `pytest`
|
||||
* **CORS**
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Full Stack FastAPI Template { #full-stack-fastapi-template }
|
||||
|
||||
Templates, while typically come with a specific setup, are designed to be flexible and customizable. This allows you to modify and adapt them to your project's requirements, making them an excellent starting point. 🏁
|
||||
Templates, while they typically come with a specific setup, are designed to be flexible and customizable. This allows you to modify and adapt them to your project's requirements, making them an excellent starting point. 🏁
|
||||
|
||||
You can use this template to get started, as it includes a lot of the initial set up, security, database and some API endpoints already done for you.
|
||||
You can use this template to get started, as it includes a lot of the initial setup, security, database and some API endpoints already done for you.
|
||||
|
||||
GitHub Repository: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Python has support for optional "type hints" (also called "type annotations").
|
||||
|
||||
These **"type hints"** or annotations are a special syntax that allow declaring the <dfn title="for example: str, int, float, bool">type</dfn> of a variable.
|
||||
These **"type hints"** or annotations are a special syntax that allows declaring the <dfn title="for example: str, int, float, bool">type</dfn> of a variable.
|
||||
|
||||
By declaring types for your variables, editors and tools can give you better support.
|
||||
|
||||
@@ -44,7 +44,7 @@ It's a very simple program.
|
||||
|
||||
But now imagine that you were writing it from scratch.
|
||||
|
||||
At some point you would have started the definition of the function, you had the parameters ready...
|
||||
At some point you start defining the function, and you have the parameters ready...
|
||||
|
||||
But then you have to call "that method that converts the first letter to upper case".
|
||||
|
||||
@@ -80,7 +80,7 @@ Those are the "type hints":
|
||||
|
||||
{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
|
||||
|
||||
That is not the same as declaring default values like would be with:
|
||||
That is not the same as declaring default values like it would be with:
|
||||
|
||||
```Python
|
||||
first_name="john", last_name="doe"
|
||||
|
||||
@@ -13,6 +13,7 @@ from fastapi import APIRouter
|
||||
members:
|
||||
- websocket
|
||||
- include_router
|
||||
- frontend
|
||||
- get
|
||||
- put
|
||||
- post
|
||||
|
||||
@@ -18,6 +18,7 @@ from fastapi import FastAPI
|
||||
- openapi
|
||||
- websocket
|
||||
- include_router
|
||||
- frontend
|
||||
- get
|
||||
- put
|
||||
- post
|
||||
|
||||
@@ -16,7 +16,7 @@ For example:
|
||||
* 403: `status.HTTP_403_FORBIDDEN`
|
||||
* etc.
|
||||
|
||||
It can be convenient to quickly access HTTP (and WebSocket) status codes in your app, using autocompletion for the name without having to remember the integer status codes by memory.
|
||||
It can be convenient to quickly access HTTP (and WebSocket) status codes in your app, using autocompletion for the name without having to memorize the integer status codes.
|
||||
|
||||
Read more about it in the [FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ When you want to define dependencies that should be compatible with both HTTP an
|
||||
|
||||
Additional classes for handling WebSockets.
|
||||
|
||||
Provided directly by Starlette, but you can import it from `fastapi`:
|
||||
Provided directly by Starlette, but you can import them from `fastapi`:
|
||||
|
||||
```python
|
||||
from fastapi.websockets import WebSocketDisconnect, WebSocketState
|
||||
@@ -60,7 +60,7 @@ from fastapi.websockets import WebSocketDisconnect, WebSocketState
|
||||
|
||||
When a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch it.
|
||||
|
||||
You can import it directly form `fastapi`:
|
||||
You can import it directly from `fastapi`:
|
||||
|
||||
```python
|
||||
from fastapi import WebSocketDisconnect
|
||||
|
||||
@@ -7,6 +7,31 @@ hide:
|
||||
|
||||
## Latest Changes
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Add support for `app.frontend("/", directory="dist")` and `router.frontend("/", directory="dist")`. PR [#15800](https://github.com/fastapi/fastapi/pull/15800) by [@tiangolo](https://github.com/tiangolo).
|
||||
* Read the docs: [Frontend](https://fastapi.tiangolo.com/tutorial/frontend/).
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Fix typo in release notes. PR [#15807](https://github.com/fastapi/fastapi/pull/15807) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Add `app.frontend()` instructions to Agent Library Skill. PR [#15805](https://github.com/fastapi/fastapi/pull/15805) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update release notes link. PR [#15802](https://github.com/fastapi/fastapi/pull/15802) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✏️ Update white space characters in bigger apps. PR [#15801](https://github.com/fastapi/fastapi/pull/15801) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✏️ Fix grammar, typos, and broken links in docs. PR [#15694](https://github.com/fastapi/fastapi/pull/15694) by [@YuriiMotov](https://github.com/YuriiMotov).
|
||||
|
||||
### Translations
|
||||
|
||||
* 🌐 Enable Hindi docs translations. PR [#15554](https://github.com/fastapi/fastapi/pull/15554) by [@YuriiMotov](https://github.com/YuriiMotov).
|
||||
|
||||
### Internal
|
||||
|
||||
* 🐛 Fix failing test, update format for raised errors. PR [#15804](https://github.com/fastapi/fastapi/pull/15804) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Fix test-alls-green. PR [#15803](https://github.com/fastapi/fastapi/pull/15803) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Enable checking `release-notes.md` for typos. PR [#15796](https://github.com/fastapi/fastapi/pull/15796) by [@YuriiMotov](https://github.com/YuriiMotov).
|
||||
* 📝 Tweak wording about deploying to FastAPI Cloud. PR [#15793](https://github.com/fastapi/fastapi/pull/15793) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔨 Use `gpt-5.5` model in `translate.py`, specify `-chat` to avoid warnings. PR [#15792](https://github.com/fastapi/fastapi/pull/15792) by [@YuriiMotov](https://github.com/YuriiMotov).
|
||||
|
||||
## 0.137.2 (2026-06-18)
|
||||
|
||||
### Features
|
||||
@@ -63,7 +88,7 @@ Before this, `router.include_router(other_router)` would take each path operatio
|
||||
|
||||
This would mean that in the end there was only one top level router, part of the app.
|
||||
|
||||
The way it is structured here is that there are a few additional classes to handle intermediate metadata for router and route inclusion. That way the information of "router X includes Y and Y includes Z" is stored somewhere, without affecting (recreating / clonning) the final route.
|
||||
The way it is structured here is that there are a few additional classes to handle intermediate metadata for router and route inclusion. That way the information of "router X includes Y and Y includes Z" is stored somewhere, without affecting (recreating / cloning) the final route.
|
||||
|
||||
#### Non Objectives
|
||||
|
||||
@@ -82,7 +107,7 @@ Additionally, any logic that iterated on `router.routes` to modify them would no
|
||||
#### Features
|
||||
|
||||
* Adding routes (path operations) after a router is included now works, they are reflected as they are not copied.
|
||||
* Including `subrouter` in `mainrouter` can be done before adding routes (path operations) to `subrouter`, because now the the entire object is stored instead of copying the routes.
|
||||
* Including `subrouter` in `mainrouter` can be done before adding routes (path operations) to `subrouter`, because now the entire object is stored instead of copying the routes.
|
||||
* As routes are not copied, in some cases that might save some memory.
|
||||
|
||||
#### Alpha Features
|
||||
@@ -97,7 +122,7 @@ Still, for now, consider this very experimental and potentially changing and bre
|
||||
|
||||
#### Future Features Enabled
|
||||
|
||||
* Custom `APIRoute` subclasses (undocumented, but alraedy works as desccribed above)
|
||||
* Custom `APIRoute` subclasses (undocumented, but already works as described above)
|
||||
* Custom `APIRouter` subclasses (undocumented, but already works as described above)
|
||||
* Dependencies per router
|
||||
* Exception handlers per router
|
||||
@@ -404,7 +429,7 @@ Still, for now, consider this very experimental and potentially changing and bre
|
||||
### Features
|
||||
|
||||
* ✨ Add support for streaming JSON Lines and binary data with `yield`. PR [#15022](https://github.com/fastapi/fastapi/pull/15022) by [@tiangolo](https://github.com/tiangolo).
|
||||
* This also upgrades Starlette from `>=0.40.0` to `>=0.46.0`, as it's needed to properly unrwap and re-raise exceptions from exception groups.
|
||||
* This also upgrades Starlette from `>=0.40.0` to `>=0.46.0`, as it's needed to properly unwrap and re-raise exceptions from exception groups.
|
||||
* New docs: [Stream JSON Lines](https://fastapi.tiangolo.com/tutorial/stream-json-lines/).
|
||||
* And new docs: [Stream Data](https://fastapi.tiangolo.com/advanced/stream-data/).
|
||||
|
||||
@@ -1427,7 +1452,7 @@ You can read more about it in the docs for [Advanced Dependencies - Dependencies
|
||||
* 🌐 Add Persian translation for `docs/fa/docs/python-types.md`. PR [#13524](https://github.com/fastapi/fastapi/pull/13524) by [@Mohammad222PR](https://github.com/Mohammad222PR).
|
||||
* 🌐 Update Portuguese Translation for `docs/pt/docs/project-generation.md`. PR [#13875](https://github.com/fastapi/fastapi/pull/13875) by [@EdmilsonRodrigues](https://github.com/EdmilsonRodrigues).
|
||||
* 🌐 Add Persian translation for `docs/fa/docs/async.md`. PR [#13541](https://github.com/fastapi/fastapi/pull/13541) by [@Mohammad222PR](https://github.com/Mohammad222PR).
|
||||
* 🌐 Add Bangali translation for `docs/bn/about/index.md`. PR [#13882](https://github.com/fastapi/fastapi/pull/13882) by [@sajjadrahman56](https://github.com/sajjadrahman56).
|
||||
* 🌐 Add Bengali translation for `docs/bn/about/index.md`. PR [#13882](https://github.com/fastapi/fastapi/pull/13882) by [@sajjadrahman56](https://github.com/sajjadrahman56).
|
||||
|
||||
### Internal
|
||||
|
||||
@@ -2269,7 +2294,7 @@ If you want to install `fastapi` with the standard dependencies but without `fas
|
||||
* ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update workflow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
@@ -2785,7 +2810,7 @@ Discussed here: [#11522](https://github.com/fastapi/fastapi/pull/11522) and here
|
||||
* 📝 Update `security/first-steps.md`. PR [#11673](https://github.com/tiangolo/fastapi/pull/11673) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 📝 Update note in `path-params-numeric-validations.md`. PR [#11672](https://github.com/tiangolo/fastapi/pull/11672) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 📝 Tweak intro docs about `Annotated` and `Query()` params. PR [#11664](https://github.com/tiangolo/fastapi/pull/11664) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64).
|
||||
* 📝 Update JWT auth documentation to use PyJWT instead of python-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64).
|
||||
* 📝 Update docs. PR [#11603](https://github.com/tiangolo/fastapi/pull/11603) by [@alejsdev](https://github.com/alejsdev).
|
||||
* ✏️ Fix typo: convert every 're-use' to 'reuse'.. PR [#11598](https://github.com/tiangolo/fastapi/pull/11598) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* ✏️ Fix typo in `fastapi/applications.py`. PR [#11593](https://github.com/tiangolo/fastapi/pull/11593) by [@petarmaric](https://github.com/petarmaric).
|
||||
@@ -3224,7 +3249,7 @@ def my_dep():
|
||||
|
||||
### Security fixes
|
||||
|
||||
* ⬆️ Upgrade minimum version of `python-multipart` to `>=0.0.7` to fix a vulnerability when using form data with a ReDos attack. You can also simply upgrade `python-multipart`.
|
||||
* ⬆️ Upgrade minimum version of `python-multipart` to `>=0.0.7` to fix a vulnerability when using form data with a ReDoS attack. You can also simply upgrade `python-multipart`.
|
||||
|
||||
Read more in the [advisory: Content-Type Header ReDoS](https://github.com/tiangolo/fastapi/security/advisories/GHSA-qf9m-vfgh-m389).
|
||||
|
||||
@@ -4732,7 +4757,7 @@ You hopefully updated to a supported version of Python a while ago. If you haven
|
||||
### Fixes
|
||||
|
||||
* 🐛 Fix `RuntimeError` raised when `HTTPException` has a status code with no content. PR [#5365](https://github.com/tiangolo/fastapi/pull/5365) by [@iudeen](https://github.com/iudeen).
|
||||
* 🐛 Fix empty response body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel).
|
||||
* 🐛 Fix empty response body when default `status_code` is empty but the `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel).
|
||||
|
||||
### Docs
|
||||
|
||||
@@ -5094,7 +5119,7 @@ def main(
|
||||
### Internal
|
||||
|
||||
* ♻ Refactor dict value extraction to minimize key lookups `fastapi/utils.py`. PR [#3139](https://github.com/tiangolo/fastapi/pull/3139) by [@ShahriyarR](https://github.com/ShahriyarR).
|
||||
* ✅ Add tests for required nonable parameters and body fields. PR [#4907](https://github.com/tiangolo/fastapi/pull/4907) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✅ Add tests for required `None`-able parameters and body fields. PR [#4907](https://github.com/tiangolo/fastapi/pull/4907) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Fix installing Material for MkDocs Insiders in CI. PR [#4897](https://github.com/tiangolo/fastapi/pull/4897) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Add pre-commit CI instead of custom GitHub Action. PR [#4896](https://github.com/tiangolo/fastapi/pull/4896) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Add pre-commit GitHub Action workflow. PR [#4895](https://github.com/tiangolo/fastapi/pull/4895) by [@tiangolo](https://github.com/tiangolo).
|
||||
@@ -5487,7 +5512,7 @@ Soon there will be a new FastAPI release upgrading Starlette to take advantage o
|
||||
|
||||
### Internal
|
||||
|
||||
* ✨ Update GitHub Action: notify-translations, to avoid a race conditions. PR [#3989](https://github.com/tiangolo/fastapi/pull/3989) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✨ Update GitHub Action: notify-translations, to avoid race conditions. PR [#3989](https://github.com/tiangolo/fastapi/pull/3989) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ⬆️ Upgrade development `autoflake`, supporting multi-line imports. PR [#3988](https://github.com/tiangolo/fastapi/pull/3988) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ⬆️ Increase dependency ranges for tests and docs: pytest-cov, pytest-asyncio, black, httpx, sqlalchemy, databases, mkdocs-markdownextradata-plugin. PR [#3987](https://github.com/tiangolo/fastapi/pull/3987) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👥 Update FastAPI People. PR [#3986](https://github.com/tiangolo/fastapi/pull/3986) by [@github-actions[bot]](https://github.com/apps/github-actions).
|
||||
@@ -5875,7 +5900,7 @@ router = APIRouter(prefix="/users", dependencies=[Depends(some_dependency)])
|
||||
|
||||
Most of these settings are now supported in `APIRouter`, which normally lives closer to the related code, so it is recommended to use `APIRouter` when possible.
|
||||
|
||||
But `include_router` is still useful to, for example, adding options (like `dependencies`, `prefix`, and `tags`) when including a third party router, or a generic router that is shared between several projects.
|
||||
But `include_router` is still useful to, for example, add options (like `dependencies`, `prefix`, and `tags`) when including a third party router, or a generic router that is shared between several projects.
|
||||
|
||||
This PR allows setting the (mostly new) parameters (additionally to the already existing parameters):
|
||||
|
||||
@@ -5937,7 +5962,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
|
||||
|
||||
* ✏️ Fix typo in Tutorial - Path Parameters. PR [#2231](https://github.com/tiangolo/fastapi/pull/2231) by [@mariacamilagl](https://github.com/mariacamilagl).
|
||||
* ✏ Fix a stylistic error in docs. PR [#2206](https://github.com/tiangolo/fastapi/pull/2206) by [@ddobrinskiy](https://github.com/ddobrinskiy).
|
||||
* ✏ Fix capitalizaiton typo in docs. PR [#2204](https://github.com/tiangolo/fastapi/pull/2204) by [@imba-tjd](https://github.com/imba-tjd).
|
||||
* ✏ Fix capitalization typo in docs. PR [#2204](https://github.com/tiangolo/fastapi/pull/2204) by [@imba-tjd](https://github.com/imba-tjd).
|
||||
* ✏ Fix typo in docs. PR [#2179](https://github.com/tiangolo/fastapi/pull/2179) by [@ammarasmro](https://github.com/ammarasmro).
|
||||
* 📝 Update/fix links in docs to use HTTPS. PR [#2165](https://github.com/tiangolo/fastapi/pull/2165) by [@imba-tjd](https://github.com/imba-tjd).
|
||||
* ✏ Fix typos and add rewording in docs. PR [#2159](https://github.com/tiangolo/fastapi/pull/2159) by [@nukopy](https://github.com/nukopy).
|
||||
@@ -6065,7 +6090,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
|
||||
* Fix typo in docs for query parameters. PR [#1832](https://github.com/tiangolo/fastapi/pull/1832) by [@ycd](https://github.com/ycd).
|
||||
* Add docs about [Async Tests](https://fastapi.tiangolo.com/advanced/async-tests/). PR [#1619](https://github.com/tiangolo/fastapi/pull/1619) by [@empicano](https://github.com/empicano).
|
||||
* Raise an exception when using form data (`Form`, `File`) without having `python-multipart` installed.
|
||||
* Up to now the application would run, and raise an exception only when receiving a request with form data, the new behavior, raising early, will prevent from deploying applications with broken dependencies.
|
||||
* Up to now the application would run, and raise an exception only when receiving a request with form data, the new behavior, raising early, will prevent deploying applications with broken dependencies.
|
||||
* It also detects if the correct package `python-multipart` is installed instead of the incorrect `multipart` (both importable as `multipart`).
|
||||
* PR [#1851](https://github.com/tiangolo/fastapi/pull/1851) based on original PR [#1627](https://github.com/tiangolo/fastapi/pull/1627) by [@chrisngyn](https://github.com/chrisngyn), [@YKo20010](https://github.com/YKo20010), [@kx-chen](https://github.com/kx-chen).
|
||||
* Re-enable Gitter releases bot. PR [#1831](https://github.com/tiangolo/fastapi/pull/1831).
|
||||
@@ -6215,7 +6240,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
|
||||
* [Using FastAPI with Django](https://www.stavros.io/posts/fastapi-with-django/) by [Stavros Korokithakis](https://x.com/Stavros).
|
||||
* [Introducing Dispatch](https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072) by [Netflix](https://netflixtechblog.com/).
|
||||
* **Podcasts**:
|
||||
* [Build The Next Generation Of Python Web Applications With FastAPI - Episode 259 - interview to Sebastían Ramírez (tiangolo)](https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/) by [Podcast.`__init__`](https://www.pythonpodcast.com/).
|
||||
* [Build The Next Generation Of Python Web Applications With FastAPI - Episode 259 - interview to Sebastián Ramírez (tiangolo)](https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/) by [Podcast.`__init__`](https://www.pythonpodcast.com/).
|
||||
* **Talks**:
|
||||
* [PyConBY 2020: Serve ML models easily with FastAPI](https://www.youtube.com/watch?v=z9K5pwb0rt8) by [Sebastián Ramírez (tiangolo)](https://x.com/tiangolo).
|
||||
* [[VIRTUAL] Py.Amsterdam's flying Software Circus: Intro to FastAPI](https://www.youtube.com/watch?v=PnpTY1f4k2U) by [Sebastián Ramírez (tiangolo)](https://x.com/tiangolo).
|
||||
@@ -6230,7 +6255,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
|
||||
|
||||
* Allow enums to allow them to have their own schemas in OpenAPI. To support [pydantic/pydantic#1432](https://github.com/pydantic/pydantic/pull/1432) in FastAPI. PR [#1461](https://github.com/tiangolo/fastapi/pull/1461).
|
||||
* Add links for funding through [GitHub sponsors](https://github.com/sponsors/tiangolo). PR [#1425](https://github.com/tiangolo/fastapi/pull/1425).
|
||||
* Update issue template for for questions. PR [#1344](https://github.com/tiangolo/fastapi/pull/1344) by [@retnikt](https://github.com/retnikt).
|
||||
* Update issue template for questions. PR [#1344](https://github.com/tiangolo/fastapi/pull/1344) by [@retnikt](https://github.com/retnikt).
|
||||
* Update warning about storing passwords in docs. PR [#1336](https://github.com/tiangolo/fastapi/pull/1336) by [@skorokithakis](https://github.com/skorokithakis).
|
||||
* Fix typo. PR [#1326](https://github.com/tiangolo/fastapi/pull/1326) by [@chenl](https://github.com/chenl).
|
||||
* Add translation to Portuguese for [Alternatives, Inspiration and Comparisons - Alternativas, Inspiração e Comparações](https://fastapi.tiangolo.com/pt/alternatives/). PR [#1325](https://github.com/tiangolo/fastapi/pull/1325) by [@Serrones](https://github.com/Serrones).
|
||||
@@ -6621,7 +6646,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
|
||||
* When declaring a `response_model` it is used directly to generate the response content, from whatever was returned from the *path operation function*.
|
||||
* Before this, the return content was first passed through `jsonable_encoder` to ensure it was a "jsonable" object, like a `dict`, instead of an arbitrary object with attributes (like an ORM model). That's why you should make sure to update your Pydantic models for objects with attributes to use `orm_mode = True`.
|
||||
* If you don't have a `response_model`, the return object will still be passed through `jsonable_encoder` first.
|
||||
* When a `response_model` is declared, the same `response_model` type declaration won't be used as is, it will be "cloned" to create an new one (a cloned Pydantic `Field` with all the submodels cloned as well).
|
||||
* When a `response_model` is declared, the same `response_model` type declaration won't be used as is, it will be "cloned" to create a new one (a cloned Pydantic `Field` with all the submodels cloned as well).
|
||||
* This avoids/fixes a potential security issue: as the returned object is passed directly to Pydantic, if the returned object was a subclass of the `response_model` (e.g. you return a `UserInDB` that inherits from `User` but contains extra fields, like `hashed_password`, and `User` is used in the `response_model`), it would still pass the validation (because `UserInDB` is a subclass of `User`) and the object would be returned as-is, including the `hashed_password`. To fix this, the declared `response_model` is cloned, if it is a Pydantic model class (or contains Pydantic model classes in it, e.g. in a `List[Item]`), the Pydantic model class(es) will be a different one (the "cloned" one). So, an object that is a subclass won't simply pass the validation and returned as-is, because it is no longer a sub-class of the cloned `response_model`. Instead, a new Pydantic model object will be created with the contents of the returned object. So, it will be a new object (made with the data from the returned one), and will be filtered by the cloned `response_model`, containing only the declared fields as normally.
|
||||
* PR [#322](https://github.com/tiangolo/fastapi/pull/322).
|
||||
|
||||
@@ -6764,7 +6789,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
|
||||
* Add support for `dependencies` parameter:
|
||||
* A parameter in *path operation decorators*, for dependencies that should be executed but the return value is not important or not used in the *path operation function*.
|
||||
* A parameter in the `.include_router()` method of FastAPI applications and routers, to include dependencies that should be executed in each *path operation* in a router.
|
||||
* This is useful, for example, to require authentication or permissions in specific group of *path operations*.
|
||||
* This is useful, for example, to require authentication or permissions in a specific group of *path operations*.
|
||||
* Different `dependencies` can be applied to different routers.
|
||||
* These `dependencies` are run before the normal parameter dependencies. And normal dependencies are run too. They can be combined.
|
||||
* Dependencies declared in a router are executed first, then the ones defined in *path operation decorators*, and then the ones declared in normal parameters. They are all combined and executed.
|
||||
|
||||
@@ -16,10 +16,10 @@ PRs with suggestions to the language-specific LLM prompt require approval from a
|
||||
|
||||
Let's say that you want to request translations for a language that is not yet translated, not even some pages. For example, Latin.
|
||||
|
||||
* The first step would be for you to find other 2 people that would be willing to be reviewing translation PRs for that language with you.
|
||||
* The first step would be for you to find 2 other people who would be willing to be reviewing translation PRs for that language with you.
|
||||
* Once there are at least 3 people that would be willing to commit to help maintain that language, you can continue the next steps.
|
||||
* Create a new discussion following the template.
|
||||
* Tag the other 2 people that will help with the language, and ask them to confirm there they will help.
|
||||
* Tag the other 2 people that will help with the language, and ask them to confirm in the comments that they will help.
|
||||
|
||||
Once there are several people in the discussion, the FastAPI team can evaluate it and can make it an official translation.
|
||||
|
||||
|
||||
@@ -17,16 +17,16 @@ Let's say you have a file structure like this:
|
||||
```
|
||||
.
|
||||
├── app
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py
|
||||
│ ├── dependencies.py
|
||||
│ └── routers
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── items.py
|
||||
│ │ └── users.py
|
||||
│ └── internal
|
||||
│ ├── __init__.py
|
||||
│ └── admin.py
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py
|
||||
│ ├── dependencies.py
|
||||
│ └── routers
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── items.py
|
||||
│ │ └── users.py
|
||||
│ └── internal
|
||||
│ ├── __init__.py
|
||||
│ └── admin.py
|
||||
```
|
||||
|
||||
/// tip
|
||||
@@ -232,7 +232,7 @@ would mean:
|
||||
|
||||
But that file doesn't exist, our dependencies are in a file at `app/dependencies.py`.
|
||||
|
||||
Remember how our app/file structure looks like:
|
||||
Remember what our app/file structure looks like:
|
||||
|
||||
<img src="/img/tutorial/bigger-applications/package.drawio.svg">
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ Again, doing just that declaration, with **FastAPI** you get:
|
||||
|
||||
Apart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`.
|
||||
|
||||
To see all the options you have, checkout [Pydantic's Type Overview](https://docs.pydantic.dev/latest/concepts/types/). You will see some examples in the next chapter.
|
||||
To see all the options you have, check out [Pydantic's Type Overview](https://docs.pydantic.dev/latest/concepts/types/). You will see some examples in the next chapter.
|
||||
|
||||
For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`:
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ To declare a **request** body, you use [Pydantic](https://docs.pydantic.dev/) mo
|
||||
|
||||
/// note
|
||||
|
||||
To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`.
|
||||
To send data, you should use one of: `POST` (the most common), `PUT`, `DELETE` or `PATCH`.
|
||||
|
||||
Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases.
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ Here's how it might look:
|
||||
|
||||
---
|
||||
|
||||
If you use Pycharm, you can:
|
||||
If you use PyCharm, you can:
|
||||
|
||||
* Open the "Run" menu.
|
||||
* Select the option "Debug...".
|
||||
|
||||
@@ -234,6 +234,7 @@ participant operation as Path Operation
|
||||
Dependencies with `yield` have evolved over time to cover different use cases and fix some issues.
|
||||
|
||||
If you want to see what has changed in different versions of FastAPI, you can read more about it in the advanced guide, in [Advanced Dependencies - Dependencies with `yield`, `HTTPException`, `except` and Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
|
||||
|
||||
## Context Managers { #context-managers }
|
||||
|
||||
### What are "Context Managers" { #what-are-context-managers }
|
||||
|
||||
@@ -36,7 +36,7 @@ Here are some of the additional data types you can use:
|
||||
* `datetime.timedelta`:
|
||||
* A Python `datetime.timedelta`.
|
||||
* In requests and responses will be represented as a `float` of total seconds.
|
||||
* Pydantic also allows representing it as a "ISO 8601 time diff encoding", [see the docs for more info](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
|
||||
* Pydantic also allows representing it as an "ISO 8601 time diff encoding", [see the docs for more info](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
|
||||
* `frozenset`:
|
||||
* In requests and responses, treated the same as a `set`:
|
||||
* In requests, a list will be read, eliminating duplicates and converting it to a `set`.
|
||||
|
||||
@@ -18,7 +18,7 @@ If you don't know, you will learn what a "password hash" is in the [security cha
|
||||
|
||||
## Multiple models { #multiple-models }
|
||||
|
||||
Here's a general idea of how the models could look like with their password fields and the places where they are used:
|
||||
Here's a general idea of what the models could look like with their password fields and the places where they are used:
|
||||
|
||||
{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
|
||||
|
||||
@@ -142,7 +142,7 @@ The supporting additional functions `fake_password_hasher` and `fake_save_user`
|
||||
|
||||
Reducing code duplication is one of the core ideas in **FastAPI**.
|
||||
|
||||
As code duplication increments the chances of bugs, security issues, code desynchronization issues (when you update in one place but not in the others), etc.
|
||||
As code duplication increases the chances of bugs, security issues, code desynchronization issues (when you update in one place but not in the others), etc.
|
||||
|
||||
And these models are all sharing a lot of the data and duplicating attribute names and types.
|
||||
|
||||
@@ -208,4 +208,4 @@ In this case, you can use `dict`:
|
||||
|
||||
Use multiple Pydantic models and inherit freely for each case.
|
||||
|
||||
You don't need to have a single data model per entity if that entity must be able to have different "states". As the case with the user "entity" with a state including `password`, `password_hash` and no password.
|
||||
You don't need to have a single data model per entity if that entity must be able to have different "states". The **user** "entity" is an example, with states that include `password`, `password_hash`, or no password.
|
||||
|
||||
@@ -108,7 +108,7 @@ OpenAPI defines an API schema for your API. And that schema includes definitions
|
||||
|
||||
#### Check the `openapi.json` { #check-the-openapi-json }
|
||||
|
||||
If you are curious about how the raw OpenAPI schema looks like, FastAPI automatically generates a JSON (schema) with the descriptions of all your API.
|
||||
If you are curious about what the raw OpenAPI schema looks like, FastAPI automatically generates a JSON (schema) with the descriptions of all your API.
|
||||
|
||||
You can see it directly at: [http://127.0.0.1:8000/openapi.json](http://127.0.0.1:8000/openapi.json).
|
||||
|
||||
|
||||
131
docs/en/docs/tutorial/frontend.md
Normal file
131
docs/en/docs/tutorial/frontend.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# Frontend { #frontend }
|
||||
|
||||
You can serve static frontend apps with `app.frontend()` (or `router.frontend()`).
|
||||
|
||||
This is useful for frontend tools that generate static files, like React with Vite, TanStack Router, Astro, Vue, Svelte, Angular, Solid, and others.
|
||||
|
||||
With these tools, you normally have a step that builds the frontend, with a command like:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
That would generate a directory like `./dist/` with your frontend files.
|
||||
|
||||
You can use `app.frontend()` to serve that directory following the conventions needed by these frontend frameworks.
|
||||
|
||||
**FastAPI** checks *path operations* first. The frontend files are checked only if no normal route matched, so your API won't be affected.
|
||||
|
||||
## Serve a Frontend { #serve-a-frontend }
|
||||
|
||||
After building your frontend, for example with `npm run build`, put the generated files in a directory, for example, `dist`.
|
||||
|
||||
Your project structure could look like this:
|
||||
|
||||
```text
|
||||
.
|
||||
├── pyproject.toml
|
||||
├── app
|
||||
│ ├── __init__.py
|
||||
│ └── main.py
|
||||
└── dist
|
||||
├── index.html
|
||||
└── assets
|
||||
└── app.js
|
||||
```
|
||||
|
||||
Then serve it with `app.frontend()`:
|
||||
|
||||
{* ../../docs_src/frontend/tutorial001_py310.py hl[5] *}
|
||||
|
||||
With this, a request for `/assets/app.js` can serve `dist/assets/app.js`.
|
||||
|
||||
If you also have a **FastAPI** *path operation*, the *path operation* wins.
|
||||
|
||||
## Client-Side Routing { #client-side-routing }
|
||||
|
||||
Many frontend apps, including **single-page apps** (SPAs), use client-side routing. A path like `/dashboard/settings` might not be a real file but the framework would take care of handling it.
|
||||
|
||||
So, if accessing that URL directly (instead of navigating through the app), the backend should serve the frontend app from `index.html`, so that the frontend framework can then handle the client-side routing.
|
||||
|
||||
For that, use `fallback="index.html"`:
|
||||
|
||||
{* ../../docs_src/frontend/tutorial002_py310.py hl[5] *}
|
||||
|
||||
**FastAPI** uses this fallback only for requests that look like browser navigation. Missing files like JavaScript, CSS, and images still return `404`.
|
||||
|
||||
/// tip
|
||||
|
||||
By default, `fallback` has a value of `fallback="auto"`. In most cases you won't need to specify `fallback`. Read below for details.
|
||||
|
||||
///
|
||||
|
||||
This is what you would want with many frontend apps that use client-side routing, for example, React with TanStack Router, Vue, Angular, SvelteKit, or Solid.
|
||||
|
||||
## Custom 404 Page { #custom-404-page }
|
||||
|
||||
You can also serve a static `404.html` page for missing frontend paths:
|
||||
|
||||
{* ../../docs_src/frontend/tutorial003_py310.py hl[5] *}
|
||||
|
||||
That response keeps a status code of `404`.
|
||||
|
||||
In this case, **FastAPI** won't serve `index.html` for missing frontend paths. It will return the `404.html` file instead.
|
||||
|
||||
/// tip
|
||||
|
||||
By default, `fallback` has a value of `fallback="auto"`. With this, if a `404.html` file is found, it will be used as the fallback automatically.
|
||||
|
||||
So, you can normally omit the `fallback` argument.
|
||||
|
||||
///
|
||||
|
||||
This is useful with frontend tools that generate static HTML files for each page, like Astro.
|
||||
|
||||
## Fallback Auto { #fallback-auto }
|
||||
|
||||
By default, `app.frontend()` uses `fallback="auto"`.
|
||||
|
||||
If there is a `404.html` file in the frontend directory, missing frontend paths serve that file with status code `404`.
|
||||
|
||||
Otherwise, if there is an `index.html` file, missing browser navigation paths serve `index.html`, which is what many frontend apps with client-side routing expect.
|
||||
|
||||
So, in most cases you can use `app.frontend("/", directory="dist")` without specifying the `fallback` argument.
|
||||
|
||||
{* ../../docs_src/frontend/tutorial001_py310.py hl[5] *}
|
||||
|
||||
## Disable Fallback { #disable-fallback }
|
||||
|
||||
If you don't want to serve a fallback file for missing frontend paths, use `fallback=None`:
|
||||
|
||||
{* ../../docs_src/frontend/tutorial005_py310.py hl[5] *}
|
||||
|
||||
Then missing frontend paths return the normal `404`.
|
||||
|
||||
## Check Directory { #check-directory }
|
||||
|
||||
By default, `app.frontend()` checks that the directory exists when the app is created.
|
||||
|
||||
This helps catch configuration errors early. For example, if the frontend build output directory is missing, **FastAPI** will raise an error on startup.
|
||||
|
||||
If your frontend files are created later, for example by a separate build step after the app object is created, set `check_dir=False`:
|
||||
|
||||
{* ../../docs_src/frontend/tutorial006_py310.py hl[5] *}
|
||||
|
||||
With `check_dir=False`, **FastAPI** will not check the directory when the app is created. If the configured directory is still missing when a request is handled, **FastAPI** will raise an error then.
|
||||
|
||||
## Use it with `APIRouter` { #use-it-with-apirouter }
|
||||
|
||||
You can also add frontend files to an `APIRouter` and include it with a prefix:
|
||||
|
||||
{* ../../docs_src/frontend/tutorial004_py310.py hl[6,7] *}
|
||||
|
||||
In this example, frontend paths are served under `/app`.
|
||||
|
||||
Any regular *path operations* in the app will still take precedence, including in other routers.
|
||||
|
||||
## Static Build Output Only { #static-build-output-only }
|
||||
|
||||
`app.frontend()` serves files already generated by your frontend build.
|
||||
|
||||
It does not run server-side rendering. It is for frontend frameworks that generate static files, not for frameworks that need dynamic rendering on the server for each request.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Handling Errors { #handling-errors }
|
||||
|
||||
There are many situations in which you need to notify an error to a client that is using your API.
|
||||
There are many situations in which you need to report an error to a client that is using your API.
|
||||
|
||||
This client could be a browser with a frontend, a code from someone else, an IoT device, etc.
|
||||
|
||||
@@ -71,7 +71,7 @@ They are handled automatically by **FastAPI** and converted to JSON.
|
||||
|
||||
## Add custom headers { #add-custom-headers }
|
||||
|
||||
There are some situations in where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security.
|
||||
There are some situations where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security.
|
||||
|
||||
You probably won't need to use it directly in your code.
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ FastAPI has an [official extension for VS Code](https://marketplace.visualstudio
|
||||
|
||||
## Advanced User Guide { #advanced-user-guide }
|
||||
|
||||
There is also an **Advanced User Guide** that you can read later after this **Tutorial - User guide**.
|
||||
There is also an **Advanced User Guide** that you can read later after this **Tutorial - User Guide**.
|
||||
|
||||
The **Advanced User Guide** builds on this one, uses the same concepts, and teaches you some extra features.
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ You can set the following fields that are used in the OpenAPI specification and
|
||||
| `title` | `str` | The title of the API. |
|
||||
| `summary` | `str` | A short summary of the API. <small>Available since OpenAPI 3.1.0, FastAPI 0.99.0.</small> |
|
||||
| `description` | `str` | A short description of the API. It can use Markdown. |
|
||||
| `version` | `string` | The version of the API. This is the version of your own application, not of OpenAPI. For example `2.5.0`. |
|
||||
| `version` | `str` | The version of the API. This is the version of your own application, not of OpenAPI. For example `2.5.0`. |
|
||||
| `terms_of_service` | `str` | A URL to the Terms of Service for the API. If provided, this has to be a URL. |
|
||||
| `contact` | `dict` | The contact information for the exposed API. It can contain several fields. <details><summary><code>contact</code> fields</summary><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td>The identifying name of the contact person/organization.</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>The URL pointing to the contact information. MUST be in the format of a URL.</td></tr><tr><td><code>email</code></td><td><code>str</code></td><td>The email address of the contact person/organization. MUST be in the format of an email address.</td></tr></tbody></table></details> |
|
||||
| `license_info` | `dict` | The license information for the exposed API. It can contain several fields. <details><summary><code>license_info</code> fields</summary><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>str</code></td><td><strong>REQUIRED</strong> (if a <code>license_info</code> is set). The license name used for the API.</td></tr><tr><td><code>identifier</code></td><td><code>str</code></td><td>An [SPDX](https://spdx.org/licenses/) license expression for the API. The <code>identifier</code> field is mutually exclusive of the <code>url</code> field. <small>Available since OpenAPI 3.1.0, FastAPI 0.99.0.</small></td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>A URL to the license used for the API. MUST be in the format of a URL.</td></tr></tbody></table></details> |
|
||||
|
||||
@@ -98,7 +98,7 @@ It will be clearly marked as deprecated in the interactive docs:
|
||||
|
||||
<img src="/img/tutorial/path-operation-configuration/image04.png">
|
||||
|
||||
Check how deprecated and non-deprecated *path operations* look like:
|
||||
Check how deprecated and non-deprecated *path operations* look:
|
||||
|
||||
<img src="/img/tutorial/path-operation-configuration/image05.png">
|
||||
|
||||
|
||||
@@ -406,7 +406,7 @@ But if you're curious about this specific code example and you're still entertai
|
||||
|
||||
#### String with `value.startswith()` { #string-with-value-startswith }
|
||||
|
||||
Did you notice? a string using `value.startswith()` can take a tuple, and it will check each value in the tuple:
|
||||
Did you notice? A string using `value.startswith()` can take a tuple, and it will check each value in the tuple:
|
||||
|
||||
{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ As they are part of the URL, they are "naturally" strings.
|
||||
|
||||
But when you declare them with Python types (in the example above, as `int`), they are converted to that type and validated against it.
|
||||
|
||||
All the same process that applied for path parameters also applies for query parameters:
|
||||
All the same processes that apply to path parameters also apply to query parameters:
|
||||
|
||||
* Editor support (obviously)
|
||||
* Data <dfn title="converting the string that comes from an HTTP request into Python data">"parsing"</dfn>
|
||||
|
||||
@@ -60,7 +60,7 @@ Using `UploadFile` has several advantages over `bytes`:
|
||||
|
||||
* You don't have to use `File()` in the default value of the parameter.
|
||||
* It uses a "spooled" file:
|
||||
* A file stored in memory up to a maximum size limit, and after passing this limit it will be stored in disk.
|
||||
* A file stored in memory up to a maximum size limit, and after passing this limit it will be stored on disk.
|
||||
* This means that it will work well for large files like images, videos, large binaries, etc. without consuming all the memory.
|
||||
* You can get metadata from the uploaded file.
|
||||
* It has a [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) `async` interface.
|
||||
@@ -111,7 +111,7 @@ When you use the `async` methods, **FastAPI** runs the file methods in a threadp
|
||||
|
||||
## What is "Form Data" { #what-is-form-data }
|
||||
|
||||
The way HTML forms (`<form></form>`) sends the data to the server normally uses a "special" encoding for that data, it's different from JSON.
|
||||
The way HTML forms (`<form></form>`) send the data to the server normally uses a "special" encoding for that data, it's different from JSON.
|
||||
|
||||
**FastAPI** will make sure to read that data from the right place instead of JSON.
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ To declare form bodies, you need to use `Form` explicitly, because without it th
|
||||
|
||||
## About "Form Fields" { #about-form-fields }
|
||||
|
||||
The way HTML forms (`<form></form>`) sends the data to the server normally uses a "special" encoding for that data, it's different from JSON.
|
||||
The way HTML forms (`<form></form>`) send the data to the server normally uses a "special" encoding for that data, it's different from JSON.
|
||||
|
||||
**FastAPI** will make sure to read that data from the right place instead of JSON.
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ If you already know what HTTP status codes are, skip to the next section.
|
||||
|
||||
In HTTP, you send a numeric status code of 3 digits as part of the response.
|
||||
|
||||
These status codes have a name associated to recognize them, but the important part is the number.
|
||||
These status codes have an associated name to help recognize them, but the important part is the number.
|
||||
|
||||
In short:
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ Nevertheless, at the <dfn title="2023-08-26">time of writing this</dfn>, Swagger
|
||||
|
||||
### OpenAPI-specific `examples` { #openapi-specific-examples }
|
||||
|
||||
Since before **JSON Schema** supported `examples` OpenAPI had support for a different field also called `examples`.
|
||||
Since before **JSON Schema** supported `examples`, OpenAPI had support for a different field also called `examples`.
|
||||
|
||||
This **OpenAPI-specific** `examples` goes in another section in the OpenAPI specification. It goes in the **details for each *path operation***, not inside each JSON Schema.
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ And it can also be used by yourself, to debug, check and test the same applicati
|
||||
|
||||
## The `password` flow { #the-password-flow }
|
||||
|
||||
Now let's go back a bit and understand what is all that.
|
||||
Now let's go back a bit and understand what all that is.
|
||||
|
||||
The `password` "flow" is one of the ways ("flows") defined in OAuth2, to handle security and authentication.
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ First, let's create a Pydantic user model.
|
||||
|
||||
The same way we use Pydantic to declare bodies, we can use it anywhere else:
|
||||
|
||||
{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
|
||||
{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *}
|
||||
|
||||
## Create a `get_current_user` dependency { #create-a-get-current-user-dependency }
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ This ensures the endpoint takes roughly the same amount of time to respond wheth
|
||||
|
||||
/// note
|
||||
|
||||
If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc"`.
|
||||
If you check the new (fake) database `fake_users_db`, you will see what the hashed password looks like now: `"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc"`.
|
||||
|
||||
///
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ Now let's build from the previous chapter and add the missing parts to have a co
|
||||
|
||||
We are going to use **FastAPI** security utilities to get the `username` and `password`.
|
||||
|
||||
OAuth2 specifies that when using the "password flow" (that we are using) the client/user must send a `username` and `password` fields as form data.
|
||||
OAuth2 specifies that when using the "password flow" (that we are using) the client/user must send `username` and `password` fields as form data.
|
||||
|
||||
And the spec says that the fields have to be named like that. So `user-name` or `email` wouldn't work.
|
||||
|
||||
@@ -146,7 +146,7 @@ UserInDB(
|
||||
|
||||
/// note
|
||||
|
||||
For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user-in-dict).
|
||||
For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user-in-model-dump).
|
||||
|
||||
///
|
||||
|
||||
@@ -190,7 +190,7 @@ We want to get the `current_user` *only* if this user is active.
|
||||
|
||||
So, we create an additional dependency `get_current_active_user` that in turn uses `get_current_user` as a dependency.
|
||||
|
||||
Both of these dependencies will just return an HTTP error if the user doesn't exist, or if is inactive.
|
||||
Both of these dependencies will just return an HTTP error if the user doesn't exist, or is inactive.
|
||||
|
||||
So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active:
|
||||
|
||||
|
||||
@@ -201,7 +201,7 @@ Then let's create `Hero`, the actual *table model*, with the **extra fields** th
|
||||
* `id`
|
||||
* `secret_name`
|
||||
|
||||
Because `Hero` inherits form `HeroBase`, it **also** has the **fields** declared in `HeroBase`, so all the fields for `Hero` are:
|
||||
Because `Hero` inherits from `HeroBase`, it **also** has the **fields** declared in `HeroBase`, so all the fields for `Hero` are:
|
||||
|
||||
* `id`
|
||||
* `name`
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
You can serve static files automatically from a directory using `StaticFiles`.
|
||||
|
||||
/// tip
|
||||
|
||||
If you need to host a frontend, use `app.frontend()` instead, read about it in [Frontend](frontend.md).
|
||||
|
||||
`app.frontend()` uses `StaticFiles` underneath, with several additional advantages for frontends, like handling client-side routing.
|
||||
|
||||
///
|
||||
|
||||
## Use `StaticFiles` { #use-staticfiles }
|
||||
|
||||
* Import `StaticFiles`.
|
||||
@@ -33,7 +41,7 @@ The `directory="static"` refers to the name of the directory that contains your
|
||||
|
||||
The `name="static"` gives it a name that can be used internally by **FastAPI**.
|
||||
|
||||
All these parameters can be different than "`static`", adjust them with the needs and specific details of your own application.
|
||||
All these parameters can be different than "`static`", adjust them to the needs and specific details of your own application.
|
||||
|
||||
## More info { #more-info }
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Import `TestClient`.
|
||||
|
||||
Create a `TestClient` by passing your **FastAPI** application to it.
|
||||
|
||||
Create functions with a name that starts with `test_` (this is standard `pytest` conventions).
|
||||
Create functions with a name that starts with `test_` (this is a standard `pytest` convention).
|
||||
|
||||
Use the `TestClient` object the same way as you do with `httpx`.
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ $ uv venv
|
||||
|
||||
By default, `uv` will create a virtual environment in a directory called `.venv`.
|
||||
|
||||
But you could customize it passing an additional argument with the directory name.
|
||||
But you could customize it by passing an additional argument with the directory name.
|
||||
|
||||
///
|
||||
|
||||
@@ -258,7 +258,7 @@ $ python -m ensurepip --upgrade
|
||||
|
||||
</div>
|
||||
|
||||
This command will install pip if it is not already installed and also ensures that the installed version of pip is at least as recent as the one available in `ensurepip`.
|
||||
This command will install pip if it is not already installed and also ensure that the installed version of pip is at least as recent as the one available in `ensurepip`.
|
||||
|
||||
///
|
||||
|
||||
@@ -447,7 +447,7 @@ Now you're ready to start working on your project.
|
||||
|
||||
/// tip
|
||||
|
||||
Do you want to understand what's all that above?
|
||||
Do you want to understand what all that above is?
|
||||
|
||||
Continue reading. 👇🤓
|
||||
|
||||
@@ -548,7 +548,7 @@ Also, depending on your operating system (e.g. Linux, Windows, macOS), it could
|
||||
|
||||
## Where are Packages Installed { #where-are-packages-installed }
|
||||
|
||||
When you install Python, it creates some directories with some files in your computer.
|
||||
When you install Python, it creates some directories with some files on your computer.
|
||||
|
||||
Some of these directories are the ones in charge of having all the packages you install.
|
||||
|
||||
@@ -568,7 +568,7 @@ That will download a compressed file with the FastAPI code, normally from [PyPI]
|
||||
|
||||
It will also **download** files for other packages that FastAPI depends on.
|
||||
|
||||
Then it will **extract** all those files and put them in a directory in your computer.
|
||||
Then it will **extract** all those files and put them in a directory on your computer.
|
||||
|
||||
By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**.
|
||||
|
||||
@@ -846,7 +846,7 @@ This is a simple guide to get you started and teach you how everything works **u
|
||||
|
||||
There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects.
|
||||
|
||||
Once you are ready and want to use a tool to **manage the entire project**, packages dependencies, virtual environments, etc. I would suggest you try [uv](https://github.com/astral-sh/uv).
|
||||
Once you are ready and want to use a tool to **manage the entire project**, package dependencies, virtual environments, etc. I would suggest you try [uv](https://github.com/astral-sh/uv).
|
||||
|
||||
`uv` can do a lot of things, it can:
|
||||
|
||||
|
||||
@@ -133,6 +133,7 @@ nav:
|
||||
- tutorial/server-sent-events.md
|
||||
- tutorial/background-tasks.md
|
||||
- tutorial/metadata.md
|
||||
- tutorial/frontend.md
|
||||
- tutorial/static-files.md
|
||||
- tutorial/testing.md
|
||||
- tutorial/debugging.md
|
||||
@@ -303,6 +304,8 @@ extra:
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /hi/
|
||||
name: hi - हिन्दी
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<a class="announce-link" href="https://fastapicloud.com" target="_blank">
|
||||
<span class="twemoji">
|
||||
{% include ".icons/material/cloud-arrow-up.svg" %}
|
||||
</span> Join the <strong>FastAPI Cloud</strong> waiting list 🚀
|
||||
</span> Deploy on <strong>FastAPI Cloud</strong> 🚀
|
||||
</a>
|
||||
</div>
|
||||
<div class="item">
|
||||
|
||||
495
docs/hi/docs/_llm-test.md
Normal file
495
docs/hi/docs/_llm-test.md
Normal file
@@ -0,0 +1,495 @@
|
||||
# LLM परीक्षण फ़ाइल { #llm-test-file }
|
||||
|
||||
यह दस्तावेज़ यह परखता है कि <abbr title="Large Language Model - बड़ा भाषा मॉडल">LLM</abbr>, जो डॉक्यूमेंटेशन का अनुवाद करता है, `scripts/translate.py` में दिए गए `general_prompt` और `docs/{language code}/llm-prompt.md` में दिए गए भाषा-विशिष्ट प्रॉम्प्ट को समझता है या नहीं। भाषा-विशिष्ट प्रॉम्प्ट को `general_prompt` के साथ जोड़ा जाता है।
|
||||
|
||||
यहाँ जो परीक्षण जोड़े गए हैं, वे भाषा-विशिष्ट प्रॉम्प्ट के सभी डिज़ाइनर्स को दिखाई देंगे।
|
||||
|
||||
उपयोग इस प्रकार करें:
|
||||
|
||||
* एक भाषा-विशिष्ट प्रॉम्प्ट रखें - `docs/{language code}/llm-prompt.md`।
|
||||
* इस दस्तावेज़ का अपने इच्छित लक्ष्य-भाषा में नया अनुवाद करें (उदाहरण के लिए `translate.py` के `translate-page` कमांड को देखें)। यह अनुवाद `docs/{language code}/docs/_llm-test.md` के अंतर्गत बना देगा।
|
||||
* जाँचें कि अनुवाद में सब कुछ ठीक है।
|
||||
* आवश्यकता होने पर, अपने भाषा-विशिष्ट प्रॉम्प्ट, जनरल प्रॉम्प्ट या अंग्रेज़ी दस्तावेज़ में सुधार करें।
|
||||
* फिर अनुवाद में बचे हुए मुद्दों को हाथ से ठीक करें ताकि यह एक अच्छा अनुवाद बन जाए।
|
||||
* दुबारा अनुवाद करें, इस बार अच्छा अनुवाद जगह पर रहते हुए। आदर्श परिणाम होगा कि LLM अब अनुवाद में कोई परिवर्तन न करे। इसका मतलब है कि जनरल प्रॉम्प्ट और आपका भाषा-विशिष्ट प्रॉम्प्ट जितने अच्छे हो सकते हैं उतने अच्छे हैं (कभी-कभी यह कुछ यादृच्छिक-से परिवर्तन कर देगा, कारण यह है कि [LLM नियतात्मक एल्गोरिथ्म नहीं हैं](https://doublespeak.chat/#/handbook#deterministic-output))।
|
||||
|
||||
परीक्षण:
|
||||
|
||||
## कोड स्निपेट्स { #code-snippets }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
यह एक कोड स्निपेट है: `foo`। और यह एक और कोड स्निपेट है: `bar`। और एक और: `baz quux`।
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
कोड स्निपेट्स की सामग्री को ज्यों का त्यों छोड़ देना चाहिए।
|
||||
|
||||
`scripts/translate.py` में जनरल प्रॉम्प्ट के सेक्शन `### Content of code snippets` को देखें।
|
||||
|
||||
////
|
||||
|
||||
## उद्धरण { #quotes }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
कल, मेरे दोस्त ने लिखा: "अगर आप 'गलत' को सही लिखते हैं, तो आपने उसे गलत लिखा है"। जिसके जवाब में मैंने कहा: "सही, लेकिन 'गलत' गलत है '"गलत"' नहीं"।
|
||||
|
||||
/// note | टिप्पणी
|
||||
|
||||
LLM संभवतः इसे गलत अनुवादित करेगा। दिलचस्प यह है कि पुनः-अनुवाद करने पर क्या यह ठीक किया हुआ अनुवाद बनाए रखता है।
|
||||
|
||||
///
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
प्रॉम्प्ट डिज़ाइनर यह चुन सकते हैं कि वे साधारण कोट्स को टाइपोग्राफ़िक कोट्स में बदलना चाहते हैं या नहीं। उन्हें ज्यों का त्यों छोड़ना भी ठीक है।
|
||||
|
||||
उदाहरण के लिए `docs/de/llm-prompt.md` में सेक्शन `### Quotes` देखें।
|
||||
|
||||
////
|
||||
|
||||
## कोड स्निपेट्स में उद्धरण { #quotes-in-code-snippets }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
`pip install "foo[bar]"`
|
||||
|
||||
कोड स्निपेट्स में स्ट्रिंग लिटरल्स के उदाहरण: `"this"`, `'that'`.
|
||||
|
||||
कोड स्निपेट्स में स्ट्रिंग लिटरल्स का एक कठिन उदाहरण: `f"I like {'oranges' if orange else "apples"}"`
|
||||
|
||||
हार्डकोर: `Yesterday, my friend wrote: "If you spell incorrectly correctly, you have spelled it incorrectly". To which I answered: "Correct, but 'incorrectly' is incorrectly not '"incorrectly"'"`
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
... लेकिन, कोड स्निपेट्स के अंदर के उद्धरण ज्यों के त्यों रहने चाहिए।
|
||||
|
||||
////
|
||||
|
||||
## कोड ब्लॉक्स { #code-blocks }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
एक Bash कोड उदाहरण...
|
||||
|
||||
```bash
|
||||
# ब्रह्मांड के लिए अभिवादन प्रिंट करें
|
||||
echo "Hello universe"
|
||||
```
|
||||
|
||||
...और एक कंसोल कोड उदाहरण...
|
||||
|
||||
```console
|
||||
$ <font color="#4E9A06">fastapi</font> run <u style="text-decoration-style:solid">main.py</u>
|
||||
<span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span> Starting server
|
||||
Searching for package file structure
|
||||
```
|
||||
|
||||
...और एक अन्य कंसोल कोड उदाहरण...
|
||||
|
||||
```console
|
||||
// "Code" नाम की डायरेक्टरी बनाएँ
|
||||
$ mkdir code
|
||||
// उस डायरेक्टरी में जाएँ
|
||||
$ cd code
|
||||
```
|
||||
|
||||
...और एक Python कोड उदाहरण...
|
||||
|
||||
```Python
|
||||
wont_work() # यह काम नहीं करेगा 😱
|
||||
works(foo="bar") # यह काम करता है 🎉
|
||||
```
|
||||
|
||||
...और बस इतना ही।
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
कोड ब्लॉक्स के अंदर के कोड में बदलाव नहीं होना चाहिए, सिवाय टिप्पणियों (comments) के।
|
||||
|
||||
`scripts/translate.py` में जनरल प्रॉम्प्ट के सेक्शन `### Content of code blocks` को देखें।
|
||||
|
||||
////
|
||||
|
||||
## टैब और रंगीन बॉक्स { #tabs-and-colored-boxes }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
/// note | टिप्पणी
|
||||
कुछ पाठ
|
||||
///
|
||||
|
||||
/// note | तकनीकी विवरण
|
||||
कुछ पाठ
|
||||
///
|
||||
|
||||
/// tip | सुझाव
|
||||
कुछ पाठ
|
||||
///
|
||||
|
||||
/// warning | चेतावनी
|
||||
कुछ पाठ
|
||||
///
|
||||
|
||||
/// danger | खतरा
|
||||
कुछ पाठ
|
||||
///
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
टैब और `Info`/`Note`/`Warning`/आदि ब्लॉक्स में उनके शीर्षक का अनुवाद ऊर्ध्वाधर रेखा (`|`) के बाद जोड़ा जाना चाहिए।
|
||||
|
||||
`scripts/translate.py` में जनरल प्रॉम्प्ट के सेक्शन `### Special blocks` और `### Tab blocks` देखें।
|
||||
|
||||
////
|
||||
|
||||
## वेब और आंतरिक लिंक { #web-and-internal-links }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
लिंक का टेक्स्ट अनुवादित होना चाहिए, लिंक का पता अपरिवर्तित रहे:
|
||||
|
||||
* [ऊपर दिए गए शीर्षक का लिंक](#code-snippets)
|
||||
* [आंतरिक लिंक](index.md#installation)
|
||||
* [बाहरी लिंक](https://sqlmodel.tiangolo.com/)
|
||||
* [एक स्टाइल का लिंक](https://fastapi.tiangolo.com/css/styles.css)
|
||||
* [एक स्क्रिप्ट का लिंक](https://fastapi.tiangolo.com/js/logic.js)
|
||||
* [एक छवि का लिंक](https://fastapi.tiangolo.com/img/foo.jpg)
|
||||
|
||||
लिंक का टेक्स्ट अनुवादित होना चाहिए, लिंक का पता अनुवाद की ओर इशारा करना चाहिए:
|
||||
|
||||
* [FastAPI लिंक](https://fastapi.tiangolo.com/hi/)
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
लिंक अनुवादित होने चाहिए, लेकिन उनके पते अपरिवर्तित रहें। अपवाद है FastAPI डॉक्यूमेंटेशन के पेजों के पूर्ण (absolute) लिंक। उस स्थिति में लिंक अनुवाद की ओर इशारा करना चाहिए।
|
||||
|
||||
`scripts/translate.py` में जनरल प्रॉम्प्ट के सेक्शन `### Links` देखें।
|
||||
|
||||
////
|
||||
|
||||
## HTML "abbr" एलिमेंट्स { #html-abbr-elements }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
यहाँ HTML "abbr" एलिमेंट्स में लिपटी कुछ चीज़ें हैं (कुछ गढ़ी हुई भी):
|
||||
|
||||
### abbr एक पूरा वाक्यांश देता है { #the-abbr-gives-a-full-phrase }
|
||||
|
||||
* <abbr title="Getting Things Done - काम पूरे करना">GTD</abbr>
|
||||
* <abbr title="less than - से कम"><code>lt</code></abbr>
|
||||
* <abbr title="XML Web Token - XML वेब टोकन">XWT</abbr>
|
||||
* <abbr title="Parallel Server Gateway Interface - समानांतर सर्वर गेटवे इंटरफ़ेस">PSGI</abbr>
|
||||
|
||||
### abbr एक पूरा वाक्यांश और उसका स्पष्टीकरण देता है { #the-abbr-gives-a-full-phrase-and-an-explanation }
|
||||
|
||||
* <abbr title="Mozilla Developer Network - मोज़िला डेवलपर नेटवर्क: डेवलपर्स के लिए प्रलेखन, फ़ायरफ़ॉक्स टीम द्वारा लिखा गया">MDN</abbr>
|
||||
* <abbr title="Input/Output - इनपुट/आउटपुट: डिस्क का पढ़ना या लिखना, नेटवर्क संचार।">I/O</abbr>.
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
"abbr" एलिमेंट्स के "title" ऐट्रिब्यूट्स का अनुवाद कुछ विशिष्ट निर्देशों का पालन करते हुए किया जाता है।
|
||||
|
||||
अनुवाद अपने स्वयं के "abbr" एलिमेंट्स जोड़ सकते हैं जिन्हें LLM को हटाना नहीं चाहिए। जैसे अंग्रेज़ी शब्दों को समझाने के लिए।
|
||||
|
||||
`scripts/translate.py` में जनरल प्रॉम्प्ट के सेक्शन `### HTML abbr elements` देखें।
|
||||
|
||||
////
|
||||
|
||||
## HTML "dfn" एलिमेंट्स { #html-dfn-elements }
|
||||
|
||||
* <dfn title="ऐसी मशीनों का समूह जिन्हें किसी तरह से एक-दूसरे से जुड़ने और साथ काम करने के लिए कॉन्फ़िगर किया गया है।">क्लस्टर</dfn>
|
||||
* <dfn title="मशीन लर्निंग की एक विधि जो इनपुट और आउटपुट लेयर्स के बीच कई छुपी हुई लेयर्स वाले कृत्रिम न्यूरल नेटवर्क्स का उपयोग करती है, इस प्रकार एक व्यापक आंतरिक संरचना विकसित करती है">डीप लर्निंग</dfn>
|
||||
|
||||
## शीर्षक { #headings }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
### एक वेबऐप विकसित करें - एक ट्यूटोरियल { #develop-a-webapp-a-tutorial }
|
||||
|
||||
नमस्ते।
|
||||
|
||||
### टाइप हिंट्स और -एनोटेशन्स { #type-hints-and-annotations }
|
||||
|
||||
फिर से नमस्ते।
|
||||
|
||||
### सुपर- और सबक्लासेज़ { #super-and-subclasses }
|
||||
|
||||
फिर से नमस्ते।
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
शीर्षकों के लिए एकमात्र कड़ा नियम यह है कि LLM कर्ली ब्रैकेट्स के अंदर के हैश-पार्ट को अपरिवर्तित छोड़े, जिससे लिंक न टूटें।
|
||||
|
||||
`scripts/translate.py` में जनरल प्रॉम्प्ट के सेक्शन `### Headings` देखें।
|
||||
|
||||
कुछ भाषा-विशिष्ट निर्देशों के लिए, जैसे `docs/de/llm-prompt.md` में सेक्शन `### Headings` देखें।
|
||||
|
||||
////
|
||||
|
||||
## डॉक्स में प्रयुक्त शब्द { #terms-used-in-the-docs }
|
||||
|
||||
//// tab | परीक्षण
|
||||
|
||||
* आप
|
||||
* आपका
|
||||
|
||||
* उदा.
|
||||
* आदि
|
||||
|
||||
* `foo` एक `int` के रूप में
|
||||
* `bar` एक `str` के रूप में
|
||||
* `baz` एक `list` के रूप में
|
||||
|
||||
* ट्यूटोरियल - उपयोगकर्ता गाइड
|
||||
* उन्नत उपयोगकर्ता गाइड
|
||||
* SQLModel डॉक्स
|
||||
* API डॉक्स
|
||||
* स्वचालित डॉक्स
|
||||
|
||||
* डेटा साइंस
|
||||
* डीप लर्निंग
|
||||
* मशीन लर्निंग
|
||||
* डिपेंडेंसी इंजेक्शन
|
||||
* HTTP बेसिक ऑथेंटिकेशन
|
||||
* HTTP डाइजेस्ट
|
||||
* ISO फ़ॉरमैट
|
||||
* JSON Schema मानक
|
||||
* JSON स्कीमा
|
||||
* स्कीमा परिभाषा
|
||||
* पासवर्ड फ्लो
|
||||
* मोबाइल
|
||||
|
||||
* अप्रचलित
|
||||
* डिज़ाइन किया गया
|
||||
* अमान्य
|
||||
* तुरंत
|
||||
* मानक
|
||||
* डिफ़ॉल्ट
|
||||
* केस-संवेदी
|
||||
* केस-असंवेदी
|
||||
|
||||
* एप्लिकेशन को सर्व करना
|
||||
* पेज को सर्व करना
|
||||
|
||||
* ऐप
|
||||
* एप्लिकेशन
|
||||
|
||||
* रिक्वेस्ट
|
||||
* रिस्पांस
|
||||
* त्रुटि रिस्पांस
|
||||
|
||||
* पाथ ऑपरेशन
|
||||
* पाथ ऑपरेशन डेकोरेटर
|
||||
* पाथ ऑपरेशन फ़ंक्शन
|
||||
|
||||
* बॉडी
|
||||
* रिक्वेस्ट बॉडी
|
||||
* रिस्पांस बॉडी
|
||||
* JSON बॉडी
|
||||
* फॉर्म बॉडी
|
||||
* फ़ाइल बॉडी
|
||||
* फ़ंक्शन बॉडी
|
||||
|
||||
* पैरामीटर
|
||||
* बॉडी पैरामीटर
|
||||
* पाथ पैरामीटर
|
||||
* क्वेरी पैरामीटर
|
||||
* कुकी पैरामीटर
|
||||
* हेडर पैरामीटर
|
||||
* फॉर्म पैरामीटर
|
||||
* फ़ंक्शन पैरामीटर
|
||||
|
||||
* इवेंट
|
||||
* स्टार्टअप इवेंट
|
||||
* सर्वर का स्टार्टअप
|
||||
* शटडाउन इवेंट
|
||||
* लाइफस्पैन इवेंट
|
||||
|
||||
* हैंडलर
|
||||
* इवेंट हैंडलर
|
||||
* एक्सेप्शन हैंडलर
|
||||
* हैंडल करना
|
||||
|
||||
* मॉडल
|
||||
* Pydantic मॉडल
|
||||
* डेटा मॉडल
|
||||
* डेटाबेस मॉडल
|
||||
* फॉर्म मॉडल
|
||||
* मॉडल ऑब्जेक्ट
|
||||
|
||||
* क्लास
|
||||
* बेस क्लास
|
||||
* पैरेंट क्लास
|
||||
* सबक्लास
|
||||
* चाइल्ड क्लास
|
||||
* सिब्लिंग क्लास
|
||||
* क्लास मेथड
|
||||
|
||||
* हेडर
|
||||
* हेडर्स
|
||||
* ऑथराइज़ेशन हेडर
|
||||
* `Authorization` हेडर
|
||||
* फॉरवर्डेड हेडर
|
||||
|
||||
* डिपेंडेंसी इंजेक्शन सिस्टम
|
||||
* डिपेंडेंसी
|
||||
* डिपेंडेबल
|
||||
* डिपेन्डन्ट
|
||||
|
||||
* I/O बाउंड
|
||||
* CPU बाउंड
|
||||
* समकालिकता
|
||||
* समान्तरता
|
||||
* मल्टीप्रोसेसिंग
|
||||
|
||||
* env var
|
||||
* पर्यावरण चर
|
||||
* `PATH`
|
||||
* `PATH` वेरिएबल
|
||||
|
||||
* प्रमाणीकरण
|
||||
* प्रमाणीकरण प्रदाता
|
||||
* अधिकारीकरण
|
||||
* अधिकारीकरण फॉर्म
|
||||
* अधिकारीकरण प्रदाता
|
||||
* उपयोगकर्ता प्रमाणीकरण करता है
|
||||
* सिस्टम उपयोगकर्ता का प्रमाणीकरण करता है
|
||||
|
||||
* CLI
|
||||
* कमांड लाइन इंटरफेस
|
||||
|
||||
* सर्वर
|
||||
* क्लाइंट
|
||||
|
||||
* क्लाउड प्रदाता
|
||||
* क्लाउड सेवा
|
||||
|
||||
* विकास
|
||||
* विकास चरण
|
||||
|
||||
* dict
|
||||
* डिक्शनरी
|
||||
* एन्युमरेशन
|
||||
* एनम
|
||||
* एनम सदस्य
|
||||
|
||||
* एन्कोडर
|
||||
* डीकोडर
|
||||
* एन्कोड करना
|
||||
* डीकोड करना
|
||||
|
||||
* एक्सेप्शन
|
||||
* रेज़ करना
|
||||
|
||||
* एक्सप्रेशन
|
||||
* स्टेटमेंट
|
||||
|
||||
* फ्रंटएंड
|
||||
* बैकएंड
|
||||
|
||||
* GitHub चर्चा
|
||||
* GitHub इश्यू
|
||||
|
||||
* प्रदर्शन
|
||||
* प्रदर्शन अनुकूलन
|
||||
|
||||
* रिटर्न टाइप
|
||||
* रिटर्न वैल्यू
|
||||
|
||||
* सुरक्षा
|
||||
* सुरक्षा स्कीम
|
||||
|
||||
* टास्क
|
||||
* बैकग्राउंड टास्क
|
||||
* टास्क फ़ंक्शन
|
||||
|
||||
* टेम्पलेट
|
||||
* टेम्पलेट इंजन
|
||||
|
||||
* टाइप एनोटेशन
|
||||
* टाइप हिंट
|
||||
|
||||
* सर्वर वर्कर
|
||||
* Uvicorn वर्कर
|
||||
* Gunicorn Worker
|
||||
* वर्कर प्रोसेस
|
||||
* वर्कर क्लास
|
||||
* वर्कलोड
|
||||
|
||||
* डिप्लॉयमेंट
|
||||
* डिप्लॉय करना
|
||||
|
||||
* SDK
|
||||
* सॉफ़्टवेयर डेवलपमेंट किट
|
||||
|
||||
* `APIRouter`
|
||||
* `requirements.txt`
|
||||
* Bearer Token
|
||||
* ब्रेकिंग चेंज
|
||||
* बग
|
||||
* बटन
|
||||
* कॉल करने योग्य
|
||||
* कोड
|
||||
* कमिट
|
||||
* कॉन्टेक्स्ट मैनेजर
|
||||
* कोरूटीन
|
||||
* डेटाबेस सेशन
|
||||
* डिस्क
|
||||
* डोमेन
|
||||
* इंजन
|
||||
* नकली X
|
||||
* HTTP GET मेथड
|
||||
* आइटम
|
||||
* लाइब्रेरी
|
||||
* लाइफस्पैन
|
||||
* लॉक
|
||||
* मिडलवेयर
|
||||
* मोबाइल एप्लिकेशन
|
||||
* मॉड्यूल
|
||||
* माउंटिंग
|
||||
* नेटवर्क
|
||||
* ओरिजिन
|
||||
* ओवरराइड
|
||||
* पेलोड
|
||||
* प्रोसेसर
|
||||
* प्रॉपर्टी
|
||||
* प्रॉक्सी
|
||||
* पुल रिक्वेस्ट
|
||||
* क्वेरी
|
||||
* RAM
|
||||
* रिमोट मशीन
|
||||
* स्टेटस कोड
|
||||
* स्ट्रिंग
|
||||
* टैग
|
||||
* वेब फ़्रेमवर्क
|
||||
* वाइल्डकार्ड
|
||||
* वापस करना
|
||||
* सत्यापित करना
|
||||
|
||||
////
|
||||
|
||||
//// tab | जानकारी
|
||||
|
||||
यह डॉक्स में दिखने वाले (ज़्यादातर) तकनीकी शब्दों की न तो पूर्ण और न ही मानक सूची है। यह प्रॉम्प्ट डिज़ाइनर को यह समझने में मदद कर सकती है कि किन शब्दों के लिए LLM को सहायक निर्देशों की ज़रूरत है। उदाहरण के लिए जब यह एक अच्छे अनुवाद को कमतर अनुवाद में वापस बदल देता है। या जब इसे आपकी भाषा में किसी शब्द का रूपांतरण/विभक्ति करने में समस्या होती है।
|
||||
|
||||
उदाहरण के लिए `docs/de/llm-prompt.md` में सेक्शन `### List of English terms and their preferred German translations` देखें।
|
||||
|
||||
////
|
||||
585
docs/hi/docs/index.md
Normal file
585
docs/hi/docs/index.md
Normal file
@@ -0,0 +1,585 @@
|
||||
---
|
||||
include_yaml:
|
||||
sponsors: data/sponsors.yml
|
||||
---
|
||||
|
||||
# FastAPI { #fastapi }
|
||||
|
||||
<style>
|
||||
.md-content .md-typeset h1 { display: none; }
|
||||
</style>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://fastapi.tiangolo.com/hi"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<em>FastAPI फ़्रेमवर्क, उच्च प्रदर्शन, सीखने में आसान, कोड लिखने में तेज़, प्रोडक्शन के लिए तैयार</em>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster">
|
||||
<img src="https://github.com/fastapi/fastapi/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="टेस्ट">
|
||||
</a>
|
||||
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/fastapi">
|
||||
<img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/fastapi.svg" alt="कवरेज">
|
||||
</a>
|
||||
<a href="https://pypi.org/project/fastapi">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="पैकेज संस्करण">
|
||||
</a>
|
||||
<a href="https://pypi.org/project/fastapi">
|
||||
<img src="https://img.shields.io/pypi/pyversions/fastapi.svg?color=%2334D058" alt="समर्थित Python संस्करण">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**दस्तावेज़**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com/hi)
|
||||
|
||||
**स्रोत कोड**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)
|
||||
|
||||
---
|
||||
|
||||
FastAPI एक आधुनिक, तेज़ (उच्च-प्रदर्शन) वेब फ़्रेमवर्क है जो मानक Python type hints के आधार पर Python से APIs बनाने के लिए है।
|
||||
|
||||
मुख्य विशेषताएँ:
|
||||
|
||||
* **तेज़**: बहुत उच्च प्रदर्शन, **NodeJS** और **Go** के समकक्ष (Starlette और Pydantic की बदौलत)। [उपलब्ध सबसे तेज़ Python फ़्रेमवर्क्स में से एक](#performance)।
|
||||
* **कोड लिखने में तेज़**: फ़ीचर्स विकसित करने की गति लगभग 200% से 300% तक बढ़ाएँ। *
|
||||
* **कम बग्स**: मानवीय (डेवलपर) त्रुटियों में लगभग 40% की कमी। *
|
||||
* **सहज**: बेहतरीन एडिटर सपोर्ट। हर जगह <dfn title="उर्फ़: ऑटो-कम्प्लीट, ऑटोकम्प्लीशन, IntelliSense">ऑटो-कम्प्लीट</dfn>। डिबगिंग में कम समय।
|
||||
* **आसान**: इस्तेमाल और सीखने में आसान। दस्तावेज़ पढ़ने में कम समय।
|
||||
* **संक्षिप्त**: कोड डुप्लीकेशन को न्यूनतम करें। प्रत्येक parameter declaration से कई फ़ीचर्स। कम बग्स।
|
||||
* **मजबूत**: प्रोडक्शन-रेडी कोड प्राप्त करें। स्वतः इंटरैक्टिव दस्तावेज़ीकरण के साथ।
|
||||
* **मानकों पर आधारित**: APIs के खुले मानकों पर आधारित (और पूर्णतः अनुकूल): [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (जिसे पहले Swagger कहा जाता था) और [JSON Schema](https://json-schema.org/)।
|
||||
|
||||
<small>* आंतरिक डेवलपमेंट टीम द्वारा प्रोडक्शन ऐप्स बनाते समय किए गए परीक्षणों के आधार पर अनुमान।</small>
|
||||
|
||||
## प्रायोजक { #sponsors }
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
### कीस्टोन प्रायोजक { #keystone-sponsor }
|
||||
|
||||
<div class="fastapi-sponsors fastapi-sponsors--keystone">
|
||||
{% for sponsor in sponsors.keystone -%}
|
||||
<a class="fastapi-sponsors__card fastapi-sponsors__card--keystone" href="{{ sponsor.url }}" title="{{ sponsor.title }}"><img class="fastapi-sponsors__banner" src="{{ sponsor.img }}" alt="{{ sponsor.title }}"></a>
|
||||
{% endfor -%}
|
||||
</div>
|
||||
|
||||
### गोल्ड प्रायोजक { #gold-sponsors }
|
||||
|
||||
<div class="fastapi-sponsors fastapi-sponsors--gold">
|
||||
{% for sponsor in sponsors.gold -%}
|
||||
<a class="fastapi-sponsors__card fastapi-sponsors__card--gold" href="{{ sponsor.url }}" title="{{ sponsor.title }}"><img class="fastapi-sponsors__banner" src="{{ sponsor.img }}" alt="{{ sponsor.title }}" loading="lazy"></a>
|
||||
{% endfor -%}
|
||||
</div>
|
||||
|
||||
### सिल्वर प्रायोजक { #silver-sponsors }
|
||||
|
||||
<div class="fastapi-sponsors fastapi-sponsors--silver">
|
||||
{% for sponsor in sponsors.silver -%}
|
||||
<a class="fastapi-sponsors__card fastapi-sponsors__card--silver" href="{{ sponsor.url }}" title="{{ sponsor.title }}"><img class="fastapi-sponsors__banner" src="{{ sponsor.img }}" alt="{{ sponsor.title }}" loading="lazy"></a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
[अन्य प्रायोजक](https://fastapi.tiangolo.com/hi/fastapi-people/#sponsors)
|
||||
|
||||
## विचार { #opinions }
|
||||
|
||||
<!-- only-mkdocs -->
|
||||
<div class="fastapi-opinions" data-fastapi-opinions>
|
||||
<div class="fastapi-opinions__tabs" role="tablist" aria-label="Companies using FastAPI">
|
||||
<button class="fastapi-opinions__tab" role="tab" type="button" id="fo-tab-microsoft" aria-controls="fo-panel-microsoft" aria-selected="true" tabindex="0">
|
||||
<span class="fastapi-opinions__mark"><img src="/img/logos/microsoft.svg" alt="Microsoft" loading="lazy"></span>
|
||||
</button>
|
||||
<button class="fastapi-opinions__tab" role="tab" type="button" id="fo-tab-uber" aria-controls="fo-panel-uber" aria-selected="false" tabindex="-1">
|
||||
<span class="fastapi-opinions__mark"><img src="/img/logos/uber.svg" alt="Uber" loading="lazy"></span>
|
||||
</button>
|
||||
<button class="fastapi-opinions__tab" role="tab" type="button" id="fo-tab-netflix" aria-controls="fo-panel-netflix" aria-selected="false" tabindex="-1">
|
||||
<span class="fastapi-opinions__mark"><img src="/img/logos/netflix.svg" alt="Netflix" loading="lazy"></span>
|
||||
</button>
|
||||
<button class="fastapi-opinions__tab" role="tab" type="button" id="fo-tab-cisco" aria-controls="fo-panel-cisco" aria-selected="false" tabindex="-1">
|
||||
<span class="fastapi-opinions__mark"><img src="/img/logos/cisco.svg" alt="Cisco" loading="lazy"></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="fastapi-opinions__panel" id="fo-panel-microsoft" role="tabpanel" aria-labelledby="fo-tab-microsoft" tabindex="0">
|
||||
<blockquote class="fastapi-opinions__quote">"मैं इन दिनों <strong>FastAPI</strong> का बहुत उपयोग कर रहा/रही हूँ। वास्तव में मैं अपनी टीम की <strong>Microsoft में ML सेवाओं</strong> के लिए इसे उपयोग करने की योजना बना रहा/रही हूँ। इनमें से कुछ को मुख्य <strong>Windows</strong> प्रोडक्ट और कुछ <strong>Office</strong> प्रोडक्ट्स में इंटीग्रेट किया जा रहा है।"</blockquote>
|
||||
<div class="fastapi-opinions__attr">— कबीर खान, <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26">(संदर्भ)</a></div>
|
||||
</div>
|
||||
<div class="fastapi-opinions__panel" id="fo-panel-uber" role="tabpanel" aria-labelledby="fo-tab-uber" tabindex="0" hidden>
|
||||
<blockquote class="fastapi-opinions__quote">"हमने <strong>FastAPI</strong> लाइब्रेरी अपनाई ताकि एक <strong>REST</strong> सर्वर स्पॉन किया जा सके जिसे <strong>अन्दाज़ों/अनुमानों</strong> को प्राप्त करने के लिए क्वेरी किया जा सके।" <em>[Ludwig के लिए]</em></blockquote>
|
||||
<div class="fastapi-opinions__attr">— पिएरो मोलिनो, यारोस्लाव डुडिन, साई सुमंत मिर्याला, <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/">(संदर्भ)</a></div>
|
||||
</div>
|
||||
<div class="fastapi-opinions__panel" id="fo-panel-netflix" role="tabpanel" aria-labelledby="fo-tab-netflix" tabindex="0" hidden>
|
||||
<blockquote class="fastapi-opinions__quote">"<strong>Netflix</strong> हमारे <strong>संकट प्रबंधन</strong> ऑर्केस्ट्रेशन फ़्रेमवर्क: <strong>Dispatch</strong> के ओपन-सोर्स रिलीज़ की घोषणा करते हुए प्रसन्न है!" <em>[FastAPI के साथ बनाया गया]</em></blockquote>
|
||||
<div class="fastapi-opinions__attr">— केविन ग्लिसन, मार्क विलानोवा, फॉरेस्ट मॉन्सेन, <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072">(संदर्भ)</a></div>
|
||||
</div>
|
||||
<div class="fastapi-opinions__panel" id="fo-panel-cisco" role="tabpanel" aria-labelledby="fo-tab-cisco" tabindex="0" hidden>
|
||||
<blockquote class="fastapi-opinions__quote">"यदि कोई प्रोडक्शन Python API बनाना चाहता है, तो मैं <strong>FastAPI</strong> की अत्यधिक अनुशंसा करूंगा/करूंगी। यह <strong>सुंदरता से डिज़ाइन</strong> किया गया है, <strong>उपयोग में सरल</strong> है और <strong>बेहद स्केलेबल</strong> है — यह हमारी API-फर्स्ट डेवलपमेंट रणनीति का <strong>मुख्य घटक</strong> बन गया है।"</blockquote>
|
||||
<div class="fastapi-opinions__attr">— डीयोन पिल्सबरी, <strong>Cisco</strong> <a href="https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/">(संदर्भ)</a></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- /only-mkdocs -->
|
||||
|
||||
<div class="only-github" markdown="1">
|
||||
|
||||
"_[...] मैं इन दिनों **FastAPI** का बहुत उपयोग कर रहा/रही हूँ। [...] वास्तव में मैं अपनी टीम की **Microsoft में ML सेवाओं** के लिए इसे उपयोग करने की योजना बना रहा/रही हूँ। इनमें से कुछ को मुख्य **Windows** प्रोडक्ट और कुछ **Office** प्रोडक्ट्स में इंटीग्रेट किया जा रहा है._"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">कबीर खान - <strong>Microsoft</strong> <a href="https://github.com/fastapi/fastapi/pull/26"><small>(संदर्भ)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_हमने **FastAPI** लाइब्रेरी अपनाई ताकि एक **REST** सर्वर स्पॉन किया जा सके जिसे **अनुमानों** को प्राप्त करने के लिए क्वेरी किया जा सके। [Ludwig के लिए]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">पिएरो मोलिनो, यारोस्लाव डुडिन, और साई सुमंत मिर्याला - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/"><small>(संदर्भ)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_**Netflix** हमारे **संकट प्रबंधन** ऑर्केस्ट्रेशन फ़्रेमवर्क: **Dispatch** के ओपन-सोर्स रिलीज़ की घोषणा करते हुए प्रसन्न है! [**FastAPI** के साथ बनाया गया]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">केविन ग्लिसन, मार्क विलानोवा, फॉरेस्ट मॉन्सेन - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072"><small>(संदर्भ)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_यदि कोई प्रोडक्शन Python API बनाना चाहता है, तो मैं **FastAPI** की अत्यधिक अनुशंसा करूंगा/करूंगी। यह **सुंदरता से डिज़ाइन** किया गया है, **उपयोग में सरल** है और **बेहद स्केलेबल** है, यह हमारी API-फ़र्स्ट डेवलपमेंट रणनीति का **मुख्य घटक** बन गया है और हमारे Virtual TAC Engineer जैसे कई ऑटोमेशन्स और सेवाओं को चला रहा है._"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">डीयोन पिल्सबरी - <strong>Cisco</strong> <a href="https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/"><small>(संदर्भ)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
</div>
|
||||
|
||||
## FastAPI कॉन्फ़ { #fastapi-conf }
|
||||
|
||||
[**FastAPI Conf '26**](https://fastapiconf.com) **28 अक्टूबर, 2026** को **एम्स्टर्डम, नीदरलैंड्स** में हो रही है। सब कुछ FastAPI के बारे में, सीधे स्रोत से। 🎤
|
||||
|
||||
<a class="fastapi-feature-banner" href="https://fastapiconf.com"><img src="https://fastapi.tiangolo.com/img/fastapi-conf.jpeg" alt="FastAPI Conf '26 - 28 अक्टूबर, 2026 - एम्स्टर्डम, NL"></a>
|
||||
|
||||
## FastAPI मिनी डॉक्यूमेंट्री { #fastapi-mini-documentary }
|
||||
|
||||
साल 2025 के अंत में एक [FastAPI मिनी डॉक्यूमेंट्री](https://www.youtube.com/watch?v=mpR8ngthqiE) रिलीज़ हुई, आप इसे ऑनलाइन देख सकते हैं:
|
||||
|
||||
<a class="fastapi-feature-banner" href="https://www.youtube.com/watch?v=mpR8ngthqiE"><img src="https://fastapi.tiangolo.com/img/fastapi-documentary.jpg" alt="FastAPI मिनी डॉक्यूमेंट्री"></a>
|
||||
|
||||
## **Typer**, CLIs का FastAPI { #typer-the-fastapi-of-clis }
|
||||
|
||||
<a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
|
||||
|
||||
यदि आप वेब API के बजाय टर्मिनल में उपयोग होने वाला <abbr title="Command Line Interface - आदेश पंक्ति इंटरफ़ेस">CLI</abbr> ऐप बना रहे हैं, तो [**Typer**](https://typer.tiangolo.com/) देखें।
|
||||
|
||||
**Typer**, FastAPI का छोटा भाई/बहन है। और इसका उद्देश्य **CLIs का FastAPI** होना है। ⌨️ 🚀
|
||||
|
||||
## आवश्यकताएँ { #requirements }
|
||||
|
||||
FastAPI दिग्गजों के कंधों पर खड़ा है:
|
||||
|
||||
* वेब हिस्सों के लिए [Starlette](https://www.starlette.dev/)।
|
||||
* डेटा हिस्सों के लिए [Pydantic](https://docs.pydantic.dev/)।
|
||||
|
||||
## स्थापना { #installation }
|
||||
|
||||
एक [वर्चुअल एन्वायरनमेंट](https://fastapi.tiangolo.com/hi/virtual-environments/) बनाएँ और सक्रिय करें, और फिर FastAPI स्थापित करें:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "fastapi[standard]"
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
**नोट**: सुनिश्चित करें कि आप सभी टर्मिनलों में काम करने के लिए `"fastapi[standard]"` को उद्धरण-चिह्नों में रखें।
|
||||
|
||||
## उदाहरण { #example }
|
||||
|
||||
### इसे बनाएँ { #create-it }
|
||||
|
||||
`main.py` फ़ाइल बनाएँ और इसमें लिखें:
|
||||
|
||||
```Python
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {"Hello": "World"}
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
def read_item(item_id: int, q: str | None = None):
|
||||
return {"item_id": item_id, "q": q}
|
||||
```
|
||||
|
||||
<details markdown="1">
|
||||
<summary>या <code>async def</code> का उपयोग करें...</summary>
|
||||
|
||||
यदि आपका कोड `async` / `await` का उपयोग करता है, तो `async def` का उपयोग करें:
|
||||
|
||||
```Python hl_lines="7 12"
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def read_root():
|
||||
return {"Hello": "World"}
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
async def read_item(item_id: int, q: str | None = None):
|
||||
return {"item_id": item_id, "q": q}
|
||||
```
|
||||
|
||||
**नोट**:
|
||||
|
||||
यदि आप नहीं जानते, तो _"जल्दी में?"_ सेक्शन देखें: दस्तावेज़ में [`async` और `await`](https://fastapi.tiangolo.com/hi/async/#in-a-hurry) के बारे में।
|
||||
|
||||
</details>
|
||||
|
||||
### इसे चलाएँ { #run-it }
|
||||
|
||||
सर्वर को इस कमांड से चलाएँ:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ fastapi dev
|
||||
|
||||
╭────────── FastAPI CLI - Development mode ───────────╮
|
||||
│ │
|
||||
│ Serving at: http://127.0.0.1:8000 │
|
||||
│ │
|
||||
│ API docs: http://127.0.0.1:8000/docs │
|
||||
│ │
|
||||
│ Running in development mode, for production use: │
|
||||
│ │
|
||||
│ fastapi run │
|
||||
│ │
|
||||
╰─────────────────────────────────────────────────────╯
|
||||
|
||||
INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
|
||||
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
INFO: Started reloader process [2248755] using WatchFiles
|
||||
INFO: Started server process [2248757]
|
||||
INFO: Waiting for application startup.
|
||||
INFO: Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
<details markdown="1">
|
||||
<summary><code>fastapi dev</code> कमांड के बारे में...</summary>
|
||||
|
||||
`fastapi dev` कमांड आपका `main.py` फ़ाइल स्वतः पढ़ता है, उसमें **FastAPI** ऐप का पता लगाता है, और [Uvicorn](https://www.uvicorn.dev) का उपयोग करके सर्वर शुरू करता है।
|
||||
|
||||
डिफ़ॉल्ट रूप से, `fastapi dev` लोकल डेवलपमेंट के लिए auto-reload सक्षम करके शुरू होगा।
|
||||
|
||||
आप इसके बारे में और पढ़ सकते हैं: [FastAPI CLI दस्तावेज़](https://fastapi.tiangolo.com/hi/fastapi-cli/) में।
|
||||
|
||||
</details>
|
||||
|
||||
### इसे जाँचें { #check-it }
|
||||
|
||||
अपने ब्राउज़र में [http://127.0.0.1:8000/items/5?q=somequery](http://127.0.0.1:8000/items/5?q=somequery) खोलें।
|
||||
|
||||
आपको JSON प्रतिक्रिया इस प्रकार दिखेगी:
|
||||
|
||||
```JSON
|
||||
{"item_id": 5, "q": "somequery"}
|
||||
```
|
||||
|
||||
आपने पहले ही एक API बना ली है जो:
|
||||
|
||||
* _paths_ `/` और `/items/{item_id}` पर HTTP अनुरोध स्वीकार करती है।
|
||||
* दोनों _paths_ `GET` <em>operations</em> लेती हैं (जिन्हें HTTP _methods_ भी कहा जाता है)।
|
||||
* _path_ `/items/{item_id}` में एक _path parameter_ `item_id` है जो `int` होना चाहिए।
|
||||
* _path_ `/items/{item_id}` में एक वैकल्पिक `str` _query parameter_ `q` है।
|
||||
|
||||
### इंटरैक्टिव API दस्तावेज़ { #interactive-api-docs }
|
||||
|
||||
अब [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर जाएँ।
|
||||
|
||||
आपको स्वचालित इंटरैक्टिव API दस्तावेज़ीकरण दिखेगा (जो [Swagger UI](https://github.com/swagger-api/swagger-ui) द्वारा प्रदान किया जाता है):
|
||||
|
||||

|
||||
|
||||
### वैकल्पिक API दस्तावेज़ { #alternative-api-docs }
|
||||
|
||||
और अब, [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) पर जाएँ।
|
||||
|
||||
आपको वैकल्पिक स्वचालित दस्तावेज़ीकरण दिखेगा (जो [ReDoc](https://github.com/Rebilly/ReDoc) द्वारा प्रदान किया जाता है):
|
||||
|
||||

|
||||
|
||||
## उदाहरण उन्नयन { #example-upgrade }
|
||||
|
||||
अब `PUT` अनुरोध से body प्राप्त करने के लिए `main.py` फ़ाइल संशोधित करें।
|
||||
|
||||
Pydantic की बदौलत, body को मानक Python प्रकारों से घोषित करें।
|
||||
|
||||
```Python hl_lines="2 7-10 23-25"
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
price: float
|
||||
is_offer: bool | None = None
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {"Hello": "World"}
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
def read_item(item_id: int, q: str | None = None):
|
||||
return {"item_id": item_id, "q": q}
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
def update_item(item_id: int, item: Item):
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
`fastapi dev` सर्वर स्वतः रीलोड होना चाहिए।
|
||||
|
||||
### इंटरैक्टिव API दस्तावेज़ उन्नयन { #interactive-api-docs-upgrade }
|
||||
|
||||
अब [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर जाएँ।
|
||||
|
||||
* इंटरैक्टिव API दस्तावेज़ स्वतः अपडेट हो जाएगा, नए body सहित:
|
||||
|
||||

|
||||
|
||||
* "Try it out" बटन पर क्लिक करें, यह आपको parameters भरने और सीधे API के साथ इंटरेक्ट करने की अनुमति देता है:
|
||||
|
||||

|
||||
|
||||
* फिर "Execute" बटन पर क्लिक करें, यूज़र इंटरफ़ेस आपकी API से संवाद करेगा, parameters भेजेगा, परिणाम प्राप्त करेगा और उन्हें स्क्रीन पर दिखाएगा:
|
||||
|
||||

|
||||
|
||||
### वैकल्पिक API दस्तावेज़ उन्नयन { #alternative-api-docs-upgrade }
|
||||
|
||||
और अब, [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) पर जाएँ।
|
||||
|
||||
* वैकल्पिक दस्तावेज़ भी नए query parameter और body को दर्शाएगा:
|
||||
|
||||

|
||||
|
||||
### पुनरावलोकन { #recap }
|
||||
|
||||
संक्षेप में, आप parameters, body, आदि के प्रकार फ़ंक्शन parameters के रूप में **एक बार** घोषित करते हैं।
|
||||
|
||||
आप यह मानक आधुनिक Python प्रकारों से करते हैं।
|
||||
|
||||
आपको किसी नई सिंटैक्स, किसी विशेष लाइब्रेरी के methods या classes, आदि सीखने की आवश्यकता नहीं है।
|
||||
|
||||
बस मानक **Python**।
|
||||
|
||||
उदाहरण के लिए, एक `int` के लिए:
|
||||
|
||||
```Python
|
||||
item_id: int
|
||||
```
|
||||
|
||||
या एक अधिक जटिल `Item` मॉडल के लिए:
|
||||
|
||||
```Python
|
||||
item: Item
|
||||
```
|
||||
|
||||
...और केवल उसी एक घोषणा के साथ आपको मिलता है:
|
||||
|
||||
* एडिटर सपोर्ट, जिसमें शामिल है:
|
||||
* कम्प्लीशन।
|
||||
* प्रकार जाँच।
|
||||
* डेटा का वैधीकरण:
|
||||
* जब डेटा अमान्य हो तो स्वतः और स्पष्ट त्रुटियाँ।
|
||||
* गहराई से nested JSON objects के लिए भी वैधीकरण।
|
||||
* इनपुट डेटा का <dfn title="उर्फ़: सीरियलाइज़ेशन, पार्सिंग, मार्शलिंग">रूपांतरण</dfn>: नेटवर्क से Python डेटा और प्रकारों में। इनमें से पढ़ना:
|
||||
* JSON।
|
||||
* Path parameters।
|
||||
* Query parameters।
|
||||
* Cookies।
|
||||
* Headers।
|
||||
* Forms।
|
||||
* Files।
|
||||
* आउटपुट डेटा का <dfn title="उर्फ़: सीरियलाइज़ेशन, पार्सिंग, मार्शलिंग">रूपांतरण</dfn>: Python डेटा और प्रकारों से नेटवर्क डेटा (JSON के रूप में) में:
|
||||
* Python प्रकारों का रूपांतरण (`str`, `int`, `float`, `bool`, `list`, आदि)।
|
||||
* `datetime` ऑब्जेक्ट्स।
|
||||
* `UUID` ऑब्जेक्ट्स।
|
||||
* डेटाबेस मॉडल्स।
|
||||
* ...और बहुत कुछ।
|
||||
* स्वचालित इंटरैक्टिव API दस्तावेज़ीकरण, जिनमें 2 वैकल्पिक यूज़र इंटरफ़ेस शामिल हैं:
|
||||
* Swagger UI।
|
||||
* ReDoc।
|
||||
|
||||
---
|
||||
|
||||
पिछले कोड उदाहरण पर लौटते हुए, **FastAPI** यह करेगा:
|
||||
|
||||
* `GET` और `PUT` अनुरोधों के लिए path में `item_id` है, यह सत्यापित करेगा।
|
||||
* `GET` और `PUT` अनुरोधों के लिए `item_id` का प्रकार `int` है, यह सत्यापित करेगा।
|
||||
* यदि नहीं है, तो क्लाइंट को एक उपयोगी, स्पष्ट त्रुटि दिखाई देगी।
|
||||
* `GET` अनुरोधों के लिए यह जाँच करेगा कि `q` नाम का एक वैकल्पिक query parameter है (जैसे `http://127.0.0.1:8000/items/foo?q=somequery`)।
|
||||
* क्योंकि `q` parameter `= None` के साथ घोषित है, यह वैकल्पिक है।
|
||||
* `None` के बिना यह आवश्यक होता (जैसे `PUT` के मामले में body आवश्यक है)।
|
||||
* `/items/{item_id}` पर `PUT` अनुरोधों के लिए, body को JSON के रूप में पढ़ेगा:
|
||||
* यह जाँचेगा कि एक आवश्यक attribute `name` है जो `str` होना चाहिए।
|
||||
* यह जाँचेगा कि एक आवश्यक attribute `price` है जो `float` होना चाहिए।
|
||||
* यह जाँचेगा कि एक वैकल्पिक attribute `is_offer` है, जो यदि मौजूद है तो `bool` होना चाहिए।
|
||||
* यह सब गहराई से nested JSON objects के लिए भी काम करेगा।
|
||||
* JSON से और JSON में स्वतः रूपांतरण।
|
||||
* हर चीज़ को OpenAPI के साथ दस्तावेज़ित करेगा, जिसे निम्न द्वारा उपयोग किया जा सकता है:
|
||||
* इंटरैक्टिव दस्तावेज़ीकरण प्रणालियाँ।
|
||||
* कई भाषाओं के लिए स्वचालित क्लाइंट कोड जनरेशन प्रणालियाँ।
|
||||
* सीधे 2 इंटरैक्टिव दस्तावेज़ीकरण वेब इंटरफेसेज़ प्रदान करेगा।
|
||||
|
||||
---
|
||||
|
||||
हमने केवल सतह को छुआ है, लेकिन आपको पहले ही समझ आ गया होगा कि यह सब कैसे काम करता है।
|
||||
|
||||
इस पंक्ति को बदलकर देखें:
|
||||
|
||||
```Python
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
...यहाँ से:
|
||||
|
||||
```Python
|
||||
... "item_name": item.name ...
|
||||
```
|
||||
|
||||
...यहाँ तक:
|
||||
|
||||
```Python
|
||||
... "item_price": item.price ...
|
||||
```
|
||||
|
||||
...और देखें कि आपका एडिटर attributes को कैसे auto-complete करेगा और उनके प्रकार जानेगा:
|
||||
|
||||

|
||||
|
||||
अधिक फ़ीचर्स सहित एक अधिक सम्पूर्ण उदाहरण के लिए, <a href="https://fastapi.tiangolo.com/hi/tutorial/">ट्यूटोरियल - यूज़र गाइड</a> देखें।
|
||||
|
||||
**स्पॉइलर अलर्ट**: ट्यूटोरियल - यूज़र गाइड में शामिल है:
|
||||
|
||||
* विभिन्न स्थानों से **parameters** की घोषणा: **headers**, **cookies**, **form fields** और **files**।
|
||||
* `maximum_length` या `regex` जैसी **validation constraints** कैसे सेट करें।
|
||||
* एक बहुत शक्तिशाली और उपयोग में आसान **<dfn title="उर्फ़: कॉम्पोनेंट्स, रिसोर्सेज़, प्रोवाइडर्स, सर्विसेज़, इंजेक्टेबल्स">डिपेंडेंसी इंजेक्शन</dfn>** सिस्टम।
|
||||
* सुरक्षा और प्रमाणीकरण, जिसमें **OAuth2** के साथ **JWT tokens** और **HTTP Basic** auth का समर्थन शामिल है।
|
||||
* **गहराई से nested JSON मॉडल्स** घोषित करने की अधिक उन्नत (पर समान रूप से आसान) तकनीकें (Pydantic की बदौलत)।
|
||||
* [Strawberry](https://strawberry.rocks) और अन्य लाइब्रेरीज़ के साथ **GraphQL** एकीकरण।
|
||||
* कई अतिरिक्त फ़ीचर्स (Starlette की बदौलत) जैसे:
|
||||
* **WebSockets**
|
||||
* HTTPX और `pytest` पर आधारित अत्यंत आसान टेस्ट्स
|
||||
* **CORS**
|
||||
* **Cookie Sessions**
|
||||
* ...आदि।
|
||||
|
||||
### अपनी ऐप परिनियोजित करें (वैकल्पिक) { #deploy-your-app-optional }
|
||||
|
||||
आप वैकल्पिक रूप से अपनी FastAPI ऐप को [FastAPI Cloud](https://fastapicloud.com) पर एक ही कमांड से डिप्लॉय कर सकते हैं। 🚀
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ fastapi deploy
|
||||
|
||||
Deploying to FastAPI Cloud...
|
||||
|
||||
✅ Deployment successful!
|
||||
|
||||
🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
CLI आपकी FastAPI एप्लिकेशन को स्वतः पहचान लेगा और उसे क्लाउड पर डिप्लॉय करेगा। यदि आप logged in नहीं हैं, तो प्रमाणीकरण प्रक्रिया पूरी करने के लिए आपका ब्राउज़र खुलेगा।
|
||||
|
||||
बस इतना ही! अब आप उस URL पर अपनी ऐप एक्सेस कर सकते हैं। ✨
|
||||
|
||||
#### FastAPI Cloud के बारे में { #about-fastapi-cloud }
|
||||
|
||||
**[FastAPI Cloud](https://fastapicloud.com)** को **FastAPI** के ही लेखक और टीम ने बनाया है।
|
||||
|
||||
यह न्यूनतम प्रयास में किसी API को **बनाने**, **डिप्लॉय** करने और **एक्सेस** करने की प्रक्रिया को सरल बनाता है।
|
||||
|
||||
यह FastAPI के साथ ऐप्स बनाने के उसी **डेवलपर अनुभव** को उन्हें क्लाउड में **डिप्लॉय** करने तक लाता है। 🎉
|
||||
|
||||
FastAPI Cloud, *FastAPI and friends* ओपन सोर्स प्रोजेक्ट्स के लिए मुख्य प्रायोजक और फंडिंग प्रदाता है। ✨
|
||||
|
||||
#### अन्य क्लाउड प्रदाताओं पर डिप्लॉय करें { #deploy-to-other-cloud-providers }
|
||||
|
||||
FastAPI ओपन सोर्स है और मानकों पर आधारित है। आप FastAPI ऐप्स को किसी भी क्लाउड प्रदाता पर डिप्लॉय कर सकते हैं।
|
||||
|
||||
अपने क्लाउड प्रदाता के गाइड्स का पालन करें और उनके साथ FastAPI ऐप्स डिप्लॉय करें। 🤓
|
||||
|
||||
## प्रदर्शन { #performance }
|
||||
|
||||
स्वतंत्र TechEmpower बेंचमार्क दिखाते हैं कि Uvicorn के तहत चलने वाले **FastAPI** एप्लीकेशन्स [उपलब्ध सबसे तेज़ Python फ़्रेमवर्क्स में से एक](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7) हैं, केवल Starlette और Uvicorn (जो FastAPI द्वारा आंतरिक रूप से उपयोग किए जाते हैं) से नीचे। (*)
|
||||
|
||||
इसके बारे में अधिक समझने के लिए, [बेंचमार्क्स](https://fastapi.tiangolo.com/hi/benchmarks/) सेक्शन देखें।
|
||||
|
||||
## निर्भरताएँ { #dependencies }
|
||||
|
||||
FastAPI, Pydantic और Starlette पर निर्भर करता है।
|
||||
|
||||
### `standard` निर्भरताएँ { #standard-dependencies }
|
||||
|
||||
जब आप `pip install "fastapi[standard]"` के साथ FastAPI स्थापित करते हैं, तो यह `standard` समूह की वैकल्पिक निर्भरताओं के साथ आता है:
|
||||
|
||||
Pydantic द्वारा उपयोग किया गया:
|
||||
|
||||
* [`email-validator`](https://github.com/JoshData/python-email-validator) - ईमेल वैधीकरण के लिए।
|
||||
|
||||
Starlette द्वारा उपयोग किया गया:
|
||||
|
||||
* [`httpx`](https://www.python-httpx.org) - यदि आप `TestClient` का उपयोग करना चाहते हैं तो आवश्यक।
|
||||
* [`jinja2`](https://jinja.palletsprojects.com) - यदि आप डिफ़ॉल्ट टेम्पलेट कॉन्फ़िगरेशन का उपयोग करना चाहते हैं तो आवश्यक।
|
||||
* [`python-multipart`](https://github.com/Kludex/python-multipart) - यदि आप फॉर्म <dfn title="HTTP अनुरोध से आने वाली स्ट्रिंग को Python डेटा में बदलना">"पार्सिंग"</dfn> का समर्थन करना चाहते हैं, `request.form()` के साथ, तो आवश्यक।
|
||||
|
||||
FastAPI द्वारा उपयोग किया गया:
|
||||
|
||||
* [`uvicorn`](https://www.uvicorn.dev) - वह सर्वर जो आपकी एप्लिकेशन को लोड और सर्व करता है। इसमें `uvicorn[standard]` शामिल है, जिसमें उच्च-प्रदर्शन सर्विंग के लिए कुछ निर्भरताएँ (जैसे `uvloop`) शामिल हैं।
|
||||
* `fastapi-cli[standard]` - `fastapi` कमांड प्रदान करने के लिए।
|
||||
* इसमें `fastapi-cloud-cli` शामिल है, जो आपको अपनी FastAPI एप्लिकेशन को [FastAPI Cloud](https://fastapicloud.com) पर डिप्लॉय करने की अनुमति देता है।
|
||||
|
||||
### `standard` निर्भरताओं के बिना { #without-standard-dependencies }
|
||||
|
||||
यदि आप `standard` वैकल्पिक निर्भरताओं को शामिल नहीं करना चाहते, तो आप `pip install fastapi` के साथ स्थापित कर सकते हैं, `pip install "fastapi[standard]"` के बजाय।
|
||||
|
||||
### `fastapi-cloud-cli` के बिना { #without-fastapi-cloud-cli }
|
||||
|
||||
यदि आप standard निर्भरताओं के साथ लेकिन `fastapi-cloud-cli` के बिना FastAPI स्थापित करना चाहते हैं, तो `pip install "fastapi[standard-no-fastapi-cloud-cli]"` के साथ स्थापित कर सकते हैं।
|
||||
|
||||
### अतिरिक्त वैकल्पिक निर्भरताएँ { #additional-optional-dependencies }
|
||||
|
||||
कुछ अतिरिक्त निर्भरताएँ हैं जिन्हें आप स्थापित करना चाहेंगे।
|
||||
|
||||
अतिरिक्त वैकल्पिक Pydantic निर्भरताएँ:
|
||||
|
||||
* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - सेटिंग्स प्रबंधन के लिए।
|
||||
* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - Pydantic के साथ उपयोग करने के लिए अतिरिक्त प्रकारों हेतु।
|
||||
|
||||
अतिरिक्त वैकल्पिक FastAPI निर्भरताएँ:
|
||||
|
||||
* [`orjson`](https://github.com/ijl/orjson) - यदि आप `ORJSONResponse` उपयोग करना चाहते हैं तो आवश्यक।
|
||||
* [`ujson`](https://github.com/esnme/ultrajson) - यदि आप `UJSONResponse` उपयोग करना चाहते हैं तो आवश्यक।
|
||||
|
||||
## लाइसेंस { #license }
|
||||
|
||||
यह प्रोजेक्ट MIT लाइसेंस की शर्तों के अंतर्गत लाइसेंस प्राप्त है।
|
||||
11
docs/hi/docs/translation-banner.md
Normal file
11
docs/hi/docs/translation-banner.md
Normal file
@@ -0,0 +1,11 @@
|
||||
/// details | 🌐 एआई और मनुष्यों द्वारा किया गया अनुवाद
|
||||
|
||||
यह अनुवाद मनुष्यों के मार्गदर्शन में एआई द्वारा किया गया है। 🤝
|
||||
|
||||
इसमें मूल अर्थ को गलत समझने या अप्राकृतिक लगने आदि जैसी गलतियाँ हो सकती हैं। 🤖
|
||||
|
||||
आप [हमें एआई LLM को बेहतर मार्गदर्शन करने में मदद करके](https://fastapi.tiangolo.com/hi/contributing/#translations) इस अनुवाद को बेहतर बना सकते हैं।
|
||||
|
||||
[अंग्रेज़ी संस्करण](ENGLISH_VERSION_URL)
|
||||
|
||||
///
|
||||
5
docs/hi/llm-prompt.md
Normal file
5
docs/hi/llm-prompt.md
Normal file
@@ -0,0 +1,5 @@
|
||||
### Target language
|
||||
|
||||
Translate to Hindi (हिन्दी).
|
||||
|
||||
Language code: hi.
|
||||
1
docs/hi/mkdocs.yml
Normal file
1
docs/hi/mkdocs.yml
Normal file
@@ -0,0 +1 @@
|
||||
INHERIT: ../en/mkdocs.yml
|
||||
0
docs_src/frontend/__init__.py
Normal file
0
docs_src/frontend/__init__.py
Normal file
5
docs_src/frontend/tutorial001_py310.py
Normal file
5
docs_src/frontend/tutorial001_py310.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.frontend("/", directory="dist")
|
||||
5
docs_src/frontend/tutorial002_py310.py
Normal file
5
docs_src/frontend/tutorial002_py310.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.frontend("/", directory="dist", fallback="index.html")
|
||||
5
docs_src/frontend/tutorial003_py310.py
Normal file
5
docs_src/frontend/tutorial003_py310.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.frontend("/", directory="dist", fallback="404.html")
|
||||
7
docs_src/frontend/tutorial004_py310.py
Normal file
7
docs_src/frontend/tutorial004_py310.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from fastapi import APIRouter, FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
router = APIRouter()
|
||||
|
||||
router.frontend("/", directory="dist", fallback="index.html")
|
||||
app.include_router(router, prefix="/app")
|
||||
5
docs_src/frontend/tutorial005_py310.py
Normal file
5
docs_src/frontend/tutorial005_py310.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.frontend("/", directory="dist", fallback=None)
|
||||
5
docs_src/frontend/tutorial006_py310.py
Normal file
5
docs_src/frontend/tutorial006_py310.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.frontend("/", directory="dist", check_dir=False)
|
||||
@@ -288,6 +288,32 @@ There could be exceptions, but try to follow this convention.
|
||||
|
||||
Apply shared dependencies at the router level via `dependencies=[Depends(...)]`.
|
||||
|
||||
## Serve Frontend Apps
|
||||
|
||||
Use `app.frontend()` to serve a built static frontend app, for example a directory generated by Vite, Astro, Angular, Svelte, Vue, or a similar tool.
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.frontend("/", directory="dist")
|
||||
```
|
||||
|
||||
Use `router.frontend()` when the frontend belongs to an `APIRouter`; normal router prefix behavior applies when the router is included.
|
||||
|
||||
```python
|
||||
from fastapi import APIRouter, FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
router = APIRouter(prefix="/admin")
|
||||
|
||||
router.frontend("/", directory="admin-dist")
|
||||
app.include_router(router)
|
||||
```
|
||||
|
||||
`app.frontend()` and `router.frontend()` are low-priority routes: regular API routes are matched first, then frontend files and client-side routing fallbacks. Use this for single-page apps and built frontend assets instead of mounting `StaticFiles` manually.
|
||||
|
||||
## Dependency Injection
|
||||
|
||||
See [the dependency injection reference](references/dependencies.md) for detailed patterns including `yield` with `scope`, and class dependencies.
|
||||
@@ -298,7 +324,7 @@ Apply shared dependencies at the router level via `dependencies=[Depends(...)]`.
|
||||
|
||||
## Async vs Sync *path operations*
|
||||
|
||||
Use `async` *path operations* only when fully certain that the logic called inside is compatible with async and await (it's called with `await`) or that doesn't block.
|
||||
Use `async` *path operations* only when fully certain that the logic called inside is compatible with async and await (it's called with `await`) or that it doesn't block.
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI
|
||||
|
||||
@@ -5,7 +5,7 @@ Use dependencies when:
|
||||
* They can't be declared in Pydantic validation and require additional logic
|
||||
* The logic depends on external resources or could block in any other way
|
||||
* Other dependencies need their results (it's a sub-dependency)
|
||||
* The logic can be shared by multiple endpoints to do things like error early, authentication, etc.
|
||||
* The logic can be shared by multiple endpoints to do things like error early, handle authentication, etc.
|
||||
* They need to handle cleanup (e.g., DB sessions, file handles), using dependencies with `yield`
|
||||
* Their logic needs input data from the request, like headers, query parameters, etc.
|
||||
|
||||
@@ -53,7 +53,7 @@ def get_username():
|
||||
try:
|
||||
yield "Rick"
|
||||
finally:
|
||||
print("Cleanup up before response is sent")
|
||||
print("Clean up before response is sent")
|
||||
|
||||
UserNameDep = Annotated[str, Depends(get_username, scope="function")]
|
||||
|
||||
|
||||
@@ -71,6 +71,6 @@ Prefer it over SQLAlchemy.
|
||||
|
||||
## HTTPX
|
||||
|
||||
Use HTTPX for handling HTTP communication (e.g. with other APIs). It support sync and async usage.
|
||||
Use HTTPX for handling HTTP communication (e.g. with other APIs). It supports sync and async usage.
|
||||
|
||||
Prefer it over Requests.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import os
|
||||
from collections.abc import Awaitable, Callable, Coroutine, Sequence
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, TypeVar
|
||||
from typing import Annotated, Any, Literal, TypeVar
|
||||
|
||||
from annotated_doc import Doc
|
||||
from fastapi import routing
|
||||
@@ -1218,6 +1219,79 @@ class FastAPI(Starlette):
|
||||
generate_unique_id_function=generate_unique_id_function,
|
||||
)
|
||||
|
||||
def frontend(
|
||||
self,
|
||||
path: Annotated[
|
||||
str,
|
||||
Doc(
|
||||
"""
|
||||
The URL path prefix where the frontend build should be served.
|
||||
"""
|
||||
),
|
||||
],
|
||||
*,
|
||||
directory: Annotated[
|
||||
str | os.PathLike[str],
|
||||
Doc(
|
||||
"""
|
||||
The directory containing the static frontend build output.
|
||||
"""
|
||||
),
|
||||
],
|
||||
fallback: Annotated[
|
||||
Literal["auto", "index.html", "404.html"] | None,
|
||||
Doc(
|
||||
"""
|
||||
The fallback file behavior for missing frontend paths.
|
||||
"""
|
||||
),
|
||||
] = "auto",
|
||||
check_dir: Annotated[
|
||||
bool,
|
||||
Doc(
|
||||
"""
|
||||
Check that the frontend directory exists when the app is created.
|
||||
"""
|
||||
),
|
||||
] = True,
|
||||
) -> None:
|
||||
"""
|
||||
Serve a static frontend build as low-priority routes.
|
||||
|
||||
Use this for frontend tools that build static files into a directory,
|
||||
such as `dist`. **FastAPI** path operations are checked first, and
|
||||
the frontend files are checked only if no normal route matched.
|
||||
|
||||
A typical project could look like this:
|
||||
|
||||
```text
|
||||
.
|
||||
├── pyproject.toml
|
||||
├── app
|
||||
│ ├── __init__.py
|
||||
│ └── main.py
|
||||
└── dist
|
||||
├── index.html
|
||||
└── assets
|
||||
└── app.js
|
||||
```
|
||||
|
||||
Then in `app/main.py`:
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory="dist")
|
||||
```
|
||||
"""
|
||||
self.router.frontend(
|
||||
path,
|
||||
directory=directory,
|
||||
fallback=fallback,
|
||||
check_dir=check_dir,
|
||||
)
|
||||
|
||||
def api_route(
|
||||
self,
|
||||
path: str,
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import contextlib
|
||||
import copy
|
||||
import email.message
|
||||
import errno
|
||||
import functools
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import types
|
||||
from collections.abc import (
|
||||
AsyncIterator,
|
||||
@@ -28,6 +31,7 @@ from enum import Enum, IntEnum
|
||||
from typing import (
|
||||
Annotated,
|
||||
Any,
|
||||
Literal,
|
||||
Protocol,
|
||||
TypeVar,
|
||||
cast,
|
||||
@@ -80,22 +84,25 @@ from starlette import routing
|
||||
from starlette._exception_handler import wrap_app_handling_exceptions
|
||||
from starlette._utils import get_route_path, is_async_callable
|
||||
from starlette.concurrency import iterate_in_threadpool, run_in_threadpool
|
||||
from starlette.datastructures import FormData, URLPath
|
||||
from starlette.datastructures import URL, FormData, URLPath
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import (
|
||||
JSONResponse,
|
||||
PlainTextResponse,
|
||||
RedirectResponse,
|
||||
Response,
|
||||
StreamingResponse,
|
||||
)
|
||||
from starlette.routing import (
|
||||
BaseRoute,
|
||||
Match,
|
||||
NoMatchFound,
|
||||
compile_path,
|
||||
get_name,
|
||||
)
|
||||
from starlette.routing import Mount as Mount # noqa
|
||||
from starlette.staticfiles import StaticFiles
|
||||
from starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send
|
||||
from starlette.websockets import WebSocket
|
||||
from typing_extensions import deprecated
|
||||
@@ -819,6 +826,7 @@ class APIWebSocketRoute(routing.WebSocketRoute):
|
||||
|
||||
_FASTAPI_SCOPE_KEY = "fastapi"
|
||||
_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY = "effective_route_context"
|
||||
_FASTAPI_FRONTEND_PATH_KEY = "frontend_path"
|
||||
_FASTAPI_INCLUDED_ROUTER_KEY = "included_router"
|
||||
_effective_route_context_var: ContextVar[Any | None] = ContextVar(
|
||||
"fastapi_effective_route_context", default=None
|
||||
@@ -826,12 +834,25 @@ _effective_route_context_var: ContextVar[Any | None] = ContextVar(
|
||||
_SCOPE_MISSING = object()
|
||||
|
||||
|
||||
class _RouteWithPath(Protocol):
|
||||
path: str
|
||||
|
||||
|
||||
def _get_fastapi_scope(scope: Scope) -> dict[str, Any]:
|
||||
fastapi_scope = scope.setdefault(_FASTAPI_SCOPE_KEY, {})
|
||||
assert isinstance(fastapi_scope, dict)
|
||||
return fastapi_scope
|
||||
|
||||
|
||||
def _update_scope(scope: Scope, child_scope: Scope) -> None:
|
||||
fastapi_child_scope = child_scope.get(_FASTAPI_SCOPE_KEY)
|
||||
for key, value in child_scope.items():
|
||||
if key != _FASTAPI_SCOPE_KEY:
|
||||
scope[key] = value
|
||||
if isinstance(fastapi_child_scope, dict):
|
||||
_get_fastapi_scope(scope).update(fastapi_child_scope)
|
||||
|
||||
|
||||
def _get_scope_effective_route_context(scope: Scope) -> Any | None:
|
||||
return scope.get(_FASTAPI_SCOPE_KEY, {}).get(_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY)
|
||||
|
||||
@@ -1305,9 +1326,7 @@ class _RouterIncludeContext:
|
||||
dependency_overrides_provider=self.dependency_overrides_provider,
|
||||
)
|
||||
|
||||
def path_for(
|
||||
self, route: APIRoute | routing.Route | routing.WebSocketRoute | routing.Mount
|
||||
) -> str:
|
||||
def path_for(self, route: _RouteWithPath) -> str:
|
||||
return self.prefix + route.path
|
||||
|
||||
|
||||
@@ -1503,6 +1522,10 @@ class _IncludedRouter(BaseRoute):
|
||||
default_factory=list
|
||||
)
|
||||
_effective_candidates_version: int | None = None
|
||||
_effective_low_priority_routes: list["_EffectiveRouteContext"] = field(
|
||||
default_factory=list
|
||||
)
|
||||
_effective_low_priority_routes_version: int | None = None
|
||||
|
||||
def effective_candidates(self) -> list["_EffectiveRouteContext | _IncludedRouter"]:
|
||||
routes_version = self.original_router._get_routes_version()
|
||||
@@ -1525,6 +1548,28 @@ class _IncludedRouter(BaseRoute):
|
||||
self._effective_candidates_version = routes_version
|
||||
return self._effective_candidates
|
||||
|
||||
def effective_low_priority_routes(self) -> list["_EffectiveRouteContext"]:
|
||||
routes_version = self.original_router._get_routes_version()
|
||||
if routes_version == self._effective_low_priority_routes_version:
|
||||
return self._effective_low_priority_routes
|
||||
self._effective_low_priority_routes = []
|
||||
for route in self.original_router._low_priority_routes:
|
||||
route_context = self._build_effective_context(route)
|
||||
if route_context is not None:
|
||||
self._effective_low_priority_routes.append(route_context)
|
||||
for route in self.original_router.routes:
|
||||
if isinstance(route, _IncludedRouter):
|
||||
child_context = self.include_context.combine(route.include_context)
|
||||
child_branch = _IncludedRouter(
|
||||
original_router=route.original_router,
|
||||
include_context=child_context,
|
||||
)
|
||||
self._effective_low_priority_routes.extend(
|
||||
child_branch.effective_low_priority_routes()
|
||||
)
|
||||
self._effective_low_priority_routes_version = routes_version
|
||||
return self._effective_low_priority_routes
|
||||
|
||||
def _build_effective_context(
|
||||
self, route: BaseRoute
|
||||
) -> _EffectiveRouteContext | None:
|
||||
@@ -1533,6 +1578,11 @@ class _IncludedRouter(BaseRoute):
|
||||
original_route=route,
|
||||
include_context=self.include_context,
|
||||
)
|
||||
if isinstance(route, _FrontendRouteGroup):
|
||||
return _EffectiveRouteContext(
|
||||
original_route=route,
|
||||
starlette_route=route.with_prefix(self.include_context.prefix),
|
||||
)
|
||||
if isinstance(route, routing.Route):
|
||||
starlette_route: BaseRoute = routing.Route(
|
||||
self.include_context.path_for(route),
|
||||
@@ -1720,6 +1770,294 @@ def _iter_routes_with_context(
|
||||
yield route, None
|
||||
|
||||
|
||||
def _normalize_frontend_path(path: str) -> str:
|
||||
if not path:
|
||||
raise AssertionError("A frontend path cannot be empty")
|
||||
if not path.startswith("/"):
|
||||
raise AssertionError("A frontend path must start with '/'")
|
||||
if path != "/":
|
||||
path = path.rstrip("/")
|
||||
return path
|
||||
|
||||
|
||||
def _join_frontend_paths(prefix: str, path: str) -> str:
|
||||
if not prefix:
|
||||
return path
|
||||
if path == "/":
|
||||
return prefix
|
||||
return prefix + path
|
||||
|
||||
|
||||
def _frontend_path_specificity(path: str) -> int:
|
||||
if path == "/":
|
||||
return 0
|
||||
return len(path)
|
||||
|
||||
|
||||
def _get_resolved_absolute_path(path: str | os.PathLike[str]) -> str:
|
||||
return os.path.realpath(os.fspath(path))
|
||||
|
||||
|
||||
class _FrontendStaticFiles(StaticFiles):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
directory: str | os.PathLike[str],
|
||||
fallback: Literal["auto", "index.html", "404.html"] | None,
|
||||
check_dir: bool = True,
|
||||
) -> None:
|
||||
self.fallback = fallback
|
||||
if check_dir and not os.path.isdir(directory):
|
||||
raise RuntimeError(
|
||||
f"Frontend directory '{directory}' does not exist. "
|
||||
f"Resolved absolute path: '{_get_resolved_absolute_path(directory)}'"
|
||||
)
|
||||
super().__init__(
|
||||
directory=directory,
|
||||
html=True,
|
||||
check_dir=check_dir,
|
||||
follow_symlink=False,
|
||||
)
|
||||
if check_dir and fallback in {"index.html", "404.html"}:
|
||||
self._check_fallback_file(fallback)
|
||||
|
||||
def _check_fallback_file(self, fallback: str) -> None:
|
||||
_, stat_result = self.lookup_path(fallback)
|
||||
if stat_result is None or not stat.S_ISREG(stat_result.st_mode):
|
||||
raise RuntimeError(
|
||||
f"Frontend fallback file '{fallback}' does not exist in "
|
||||
f"directory '{self.directory}'. Resolved absolute directory: "
|
||||
f"'{self._get_resolved_directory()}'"
|
||||
)
|
||||
|
||||
def _get_resolved_directory(self) -> str:
|
||||
assert self.directory is not None
|
||||
return _get_resolved_absolute_path(self.directory)
|
||||
|
||||
def get_path(self, scope: Scope) -> str:
|
||||
path = _get_fastapi_scope(scope).get(_FASTAPI_FRONTEND_PATH_KEY, "")
|
||||
assert isinstance(path, str)
|
||||
return os.path.normpath(os.path.join(*path.split("/")))
|
||||
|
||||
async def get_response(self, path: str, scope: Scope) -> Response:
|
||||
if scope["method"] not in ("GET", "HEAD"):
|
||||
raise HTTPException(status_code=405)
|
||||
|
||||
try:
|
||||
full_path, stat_result = await run_in_threadpool(self.lookup_path, path)
|
||||
except PermissionError:
|
||||
raise HTTPException(status_code=401) from None
|
||||
except OSError as exc:
|
||||
if exc.errno == errno.ENAMETOOLONG:
|
||||
raise HTTPException(status_code=404) from None
|
||||
raise exc
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404) from None
|
||||
|
||||
if stat_result and stat.S_ISREG(stat_result.st_mode):
|
||||
return self.file_response(full_path, stat_result, scope)
|
||||
|
||||
if stat_result and stat.S_ISDIR(stat_result.st_mode):
|
||||
index_path = os.path.join(path, "index.html")
|
||||
full_path, stat_result = await run_in_threadpool(
|
||||
self.lookup_path, index_path
|
||||
)
|
||||
if stat_result is not None and stat.S_ISREG(stat_result.st_mode):
|
||||
if not scope["path"].endswith("/"):
|
||||
url = URL(scope=scope)
|
||||
url = url.replace(path=url.path + "/")
|
||||
return RedirectResponse(url=url)
|
||||
return self.file_response(full_path, stat_result, scope)
|
||||
|
||||
if self.fallback == "404.html" or (
|
||||
self.fallback == "auto" and self._fallback_file_exists("404.html")
|
||||
):
|
||||
return await self._fallback_response("404.html", scope, status_code=404)
|
||||
|
||||
if (
|
||||
self.fallback == "index.html"
|
||||
or (self.fallback == "auto" and self._fallback_file_exists("index.html"))
|
||||
) and _is_frontend_navigation_request(scope):
|
||||
return await self._fallback_response("index.html", scope, status_code=200)
|
||||
|
||||
raise HTTPException(status_code=404)
|
||||
|
||||
def _fallback_file_exists(self, fallback: str) -> bool:
|
||||
_, stat_result = self.lookup_path(fallback)
|
||||
return stat_result is not None and stat.S_ISREG(stat_result.st_mode)
|
||||
|
||||
async def _fallback_response(
|
||||
self, fallback: str, scope: Scope, *, status_code: int
|
||||
) -> Response:
|
||||
full_path, stat_result = await run_in_threadpool(self.lookup_path, fallback)
|
||||
if stat_result is None or not stat.S_ISREG(stat_result.st_mode):
|
||||
raise RuntimeError(
|
||||
f"Frontend fallback file '{fallback}' does not exist in "
|
||||
f"directory '{self.directory}'. Resolved absolute directory: "
|
||||
f"'{self._get_resolved_directory()}'"
|
||||
)
|
||||
return self.file_response(
|
||||
full_path, stat_result, scope, status_code=status_code
|
||||
)
|
||||
|
||||
|
||||
def _iter_accept_media_types(accept: str) -> Iterator[tuple[str, float]]:
|
||||
for raw_value in accept.split(","):
|
||||
message = email.message.Message()
|
||||
message["content-type"] = raw_value.strip()
|
||||
q = message.get_param("q")
|
||||
quality = 1.0
|
||||
if isinstance(q, str):
|
||||
try:
|
||||
quality = float(q)
|
||||
except ValueError:
|
||||
pass
|
||||
yield (
|
||||
f"{message.get_content_maintype()}/{message.get_content_subtype()}",
|
||||
quality,
|
||||
)
|
||||
|
||||
|
||||
def _is_frontend_navigation_request(scope: Scope) -> bool:
|
||||
route_path = get_route_path(scope)
|
||||
final_segment = route_path.rsplit("/", 1)[-1]
|
||||
if os.path.splitext(final_segment)[1]:
|
||||
return False
|
||||
request = Request(scope)
|
||||
wildcard_accepted = False
|
||||
html_rejected = False
|
||||
for media_type, quality in _iter_accept_media_types(
|
||||
request.headers.get("accept", "")
|
||||
):
|
||||
if media_type in {"text/html", "application/xhtml+xml"}:
|
||||
if quality == 0:
|
||||
html_rejected = True
|
||||
else:
|
||||
return True
|
||||
elif media_type == "*/*" and quality != 0:
|
||||
wildcard_accepted = True
|
||||
return wildcard_accepted and not html_rejected
|
||||
|
||||
|
||||
class _FrontendRoute(BaseRoute):
|
||||
def __init__(
|
||||
self,
|
||||
path: str,
|
||||
*,
|
||||
directory: str | os.PathLike[str],
|
||||
fallback: Literal["auto", "index.html", "404.html"] | None = "auto",
|
||||
check_dir: bool = True,
|
||||
) -> None:
|
||||
if fallback not in {"auto", "index.html", "404.html", None}:
|
||||
raise AssertionError(
|
||||
"fallback must be 'auto', 'index.html', '404.html', or None"
|
||||
)
|
||||
self.path = _normalize_frontend_path(path)
|
||||
self.methods = {"GET", "HEAD"}
|
||||
self.app = _FrontendStaticFiles(
|
||||
directory=directory, fallback=fallback, check_dir=check_dir
|
||||
)
|
||||
|
||||
def with_path(self, path: str) -> "_FrontendRoute":
|
||||
route = copy.copy(self)
|
||||
route.path = _normalize_frontend_path(path)
|
||||
return route
|
||||
|
||||
def matches(self, scope: Scope) -> tuple[Match, Scope]:
|
||||
if scope["type"] != "http":
|
||||
return Match.NONE, {}
|
||||
frontend_path = self._get_frontend_path(get_route_path(scope))
|
||||
if frontend_path is None:
|
||||
return Match.NONE, {}
|
||||
child_scope = {_FASTAPI_SCOPE_KEY: {_FASTAPI_FRONTEND_PATH_KEY: frontend_path}}
|
||||
if scope["method"] not in self.methods:
|
||||
return Match.PARTIAL, child_scope
|
||||
return Match.FULL, child_scope
|
||||
|
||||
def _get_frontend_path(self, route_path: str) -> str | None:
|
||||
if self.path == "/":
|
||||
return route_path.lstrip("/")
|
||||
if route_path == self.path:
|
||||
return ""
|
||||
prefix = self.path + "/"
|
||||
if route_path.startswith(prefix):
|
||||
return route_path[len(prefix) :]
|
||||
return None
|
||||
|
||||
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
await self.app(scope, receive, send)
|
||||
|
||||
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
|
||||
raise NoMatchFound(name, path_params)
|
||||
|
||||
|
||||
class _FrontendRouteGroup(BaseRoute):
|
||||
def __init__(self) -> None:
|
||||
self.routes: list[_FrontendRoute] = []
|
||||
|
||||
def add_frontend_route(
|
||||
self,
|
||||
path: str,
|
||||
*,
|
||||
directory: str | os.PathLike[str],
|
||||
fallback: Literal["auto", "index.html", "404.html"] | None = "auto",
|
||||
check_dir: bool = True,
|
||||
) -> None:
|
||||
self.routes.append(
|
||||
_FrontendRoute(
|
||||
path,
|
||||
directory=directory,
|
||||
fallback=fallback,
|
||||
check_dir=check_dir,
|
||||
)
|
||||
)
|
||||
|
||||
def with_prefix(self, prefix: str) -> "_FrontendRouteGroup":
|
||||
route_group = copy.copy(self)
|
||||
route_group.routes = [
|
||||
route.with_path(_join_frontend_paths(prefix, route.path))
|
||||
for route in self.routes
|
||||
]
|
||||
return route_group
|
||||
|
||||
def matches(self, scope: Scope) -> tuple[Match, Scope]:
|
||||
match, child_scope, _ = self._match(scope)
|
||||
return match, child_scope
|
||||
|
||||
def _match(self, scope: Scope) -> tuple[Match, Scope, _FrontendRoute | None]:
|
||||
full: tuple[Scope, _FrontendRoute] | None = None
|
||||
partial: tuple[Scope, _FrontendRoute] | None = None
|
||||
for route in self.routes:
|
||||
match, child_scope = route.matches(scope)
|
||||
if match == Match.FULL:
|
||||
if full is None or _frontend_path_specificity(
|
||||
route.path
|
||||
) > _frontend_path_specificity(full[1].path):
|
||||
full = (child_scope, route)
|
||||
elif match == Match.PARTIAL:
|
||||
if partial is None or _frontend_path_specificity(
|
||||
route.path
|
||||
) > _frontend_path_specificity(partial[1].path):
|
||||
partial = (child_scope, route)
|
||||
if full is not None:
|
||||
child_scope, route = full
|
||||
return Match.FULL, child_scope, route
|
||||
if partial is not None:
|
||||
child_scope, route = partial
|
||||
return Match.PARTIAL, child_scope, route
|
||||
return Match.NONE, {}, None
|
||||
|
||||
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
match, child_scope, route = self._match(scope)
|
||||
if match == Match.NONE or route is None:
|
||||
raise HTTPException(status_code=404)
|
||||
_update_scope(scope, child_scope)
|
||||
await route.handle(scope, receive, send)
|
||||
|
||||
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
|
||||
raise NoMatchFound(name, path_params)
|
||||
|
||||
|
||||
class APIRouter(routing.Router):
|
||||
"""
|
||||
`APIRouter` class, used to group *path operations*, for example to structure
|
||||
@@ -2032,6 +2370,8 @@ class APIRouter(routing.Router):
|
||||
self.generate_unique_id_function = generate_unique_id_function
|
||||
self.strict_content_type = strict_content_type
|
||||
self._routes_version = 0
|
||||
self._low_priority_routes: list[BaseRoute] = []
|
||||
self._frontend_routes: _FrontendRouteGroup | None = None
|
||||
|
||||
def _mark_routes_changed(self) -> None:
|
||||
self._routes_version += 1
|
||||
@@ -2093,6 +2433,150 @@ class APIRouter(routing.Router):
|
||||
super().add_websocket_route(path, endpoint, name=name)
|
||||
self._mark_routes_changed()
|
||||
|
||||
def frontend(
|
||||
self,
|
||||
path: Annotated[
|
||||
str,
|
||||
Doc(
|
||||
"""
|
||||
The URL path prefix where the frontend build should be served.
|
||||
"""
|
||||
),
|
||||
],
|
||||
*,
|
||||
directory: Annotated[
|
||||
str | os.PathLike[str],
|
||||
Doc(
|
||||
"""
|
||||
The directory containing the static frontend build output.
|
||||
"""
|
||||
),
|
||||
],
|
||||
fallback: Annotated[
|
||||
Literal["auto", "index.html", "404.html"] | None,
|
||||
Doc(
|
||||
"""
|
||||
The fallback file behavior for missing frontend paths.
|
||||
"""
|
||||
),
|
||||
] = "auto",
|
||||
check_dir: Annotated[
|
||||
bool,
|
||||
Doc(
|
||||
"""
|
||||
Check that the frontend directory exists when the app is created.
|
||||
"""
|
||||
),
|
||||
] = True,
|
||||
) -> None:
|
||||
"""
|
||||
Serve a static frontend build as low-priority routes.
|
||||
|
||||
Use this for frontend tools that build static files into a directory,
|
||||
such as `dist`. **FastAPI** path operations are checked first, and
|
||||
the frontend files are checked only if no normal route matched.
|
||||
|
||||
A typical project could look like this:
|
||||
|
||||
```text
|
||||
.
|
||||
├── pyproject.toml
|
||||
├── app
|
||||
│ ├── __init__.py
|
||||
│ └── main.py
|
||||
└── dist
|
||||
├── index.html
|
||||
└── assets
|
||||
└── app.js
|
||||
```
|
||||
|
||||
Then in `app/main.py`:
|
||||
|
||||
```python
|
||||
from fastapi import APIRouter, FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
router = APIRouter()
|
||||
router.frontend("/", directory="dist")
|
||||
app.include_router(router)
|
||||
```
|
||||
"""
|
||||
normalized_path = _normalize_frontend_path(path)
|
||||
if self._frontend_routes is None:
|
||||
self._frontend_routes = _FrontendRouteGroup()
|
||||
self._low_priority_routes.append(self._frontend_routes)
|
||||
self._frontend_routes.add_frontend_route(
|
||||
_join_frontend_paths(self.prefix, normalized_path),
|
||||
directory=directory,
|
||||
fallback=fallback,
|
||||
check_dir=check_dir,
|
||||
)
|
||||
self._mark_routes_changed()
|
||||
|
||||
async def app(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
assert scope["type"] in ("http", "websocket", "lifespan")
|
||||
|
||||
if "router" not in scope:
|
||||
scope["router"] = self
|
||||
|
||||
if scope["type"] == "lifespan":
|
||||
await self.lifespan(scope, receive, send)
|
||||
return
|
||||
|
||||
partial: tuple[BaseRoute, Scope] | None = None
|
||||
for route in self.routes:
|
||||
match, child_scope = route.matches(scope)
|
||||
if match == Match.FULL:
|
||||
scope.update(child_scope)
|
||||
await route.handle(scope, receive, send)
|
||||
return
|
||||
if match == Match.PARTIAL and partial is None:
|
||||
partial = (route, child_scope)
|
||||
|
||||
if partial is not None:
|
||||
route, child_scope = partial
|
||||
scope.update(child_scope)
|
||||
await route.handle(scope, receive, send)
|
||||
return
|
||||
|
||||
route_path = get_route_path(scope)
|
||||
if scope["type"] == "http" and self.redirect_slashes and route_path != "/":
|
||||
redirect_scope = dict(scope)
|
||||
if route_path.endswith("/"):
|
||||
redirect_scope["path"] = redirect_scope["path"].rstrip("/")
|
||||
else:
|
||||
redirect_scope["path"] = redirect_scope["path"] + "/"
|
||||
|
||||
for route in self.routes:
|
||||
match, _ = route.matches(redirect_scope)
|
||||
if match != Match.NONE:
|
||||
redirect_url = URL(scope=redirect_scope)
|
||||
response = RedirectResponse(url=str(redirect_url))
|
||||
await response(scope, receive, send)
|
||||
return
|
||||
|
||||
(
|
||||
low_priority_match,
|
||||
low_priority_scope,
|
||||
low_priority_route,
|
||||
low_priority_context,
|
||||
) = self._match_low_priority(scope)
|
||||
if low_priority_match != Match.NONE and low_priority_route is not None:
|
||||
_update_scope(scope, low_priority_scope)
|
||||
if low_priority_context is not None:
|
||||
_get_fastapi_scope(scope)[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = (
|
||||
low_priority_context
|
||||
)
|
||||
original_route = low_priority_context.original_route
|
||||
if isinstance(original_route, APIRoute):
|
||||
scope["route"] = original_route
|
||||
await original_route.handle(scope, receive, send)
|
||||
return
|
||||
await low_priority_route.handle(scope, receive, send)
|
||||
return
|
||||
|
||||
await self.default(scope, receive, send)
|
||||
|
||||
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
included_router = _get_scope_included_router(scope)
|
||||
if (
|
||||
@@ -2113,6 +2597,60 @@ class APIRouter(routing.Router):
|
||||
return match, child_scope
|
||||
return Match.NONE, {}
|
||||
|
||||
def _iter_low_priority_routes(
|
||||
self,
|
||||
) -> Iterator[BaseRoute | _EffectiveRouteContext]:
|
||||
yield from self._low_priority_routes
|
||||
for route in self.routes:
|
||||
if isinstance(route, _IncludedRouter):
|
||||
yield from route.effective_low_priority_routes()
|
||||
|
||||
def _match_low_priority(
|
||||
self, scope: Scope
|
||||
) -> tuple[Match, Scope, BaseRoute | None, _EffectiveRouteContext | None]:
|
||||
full: tuple[Scope, BaseRoute, _EffectiveRouteContext | None] | None = None
|
||||
partial: tuple[Scope, BaseRoute, _EffectiveRouteContext | None] | None = None
|
||||
for candidate in self._iter_low_priority_routes():
|
||||
route: BaseRoute
|
||||
if isinstance(candidate, _EffectiveRouteContext):
|
||||
route_context: _EffectiveRouteContext | None = candidate
|
||||
original_route = candidate.original_route
|
||||
if isinstance(original_route, APIRoute):
|
||||
fastapi_scope = _get_fastapi_scope(scope)
|
||||
previous_context = fastapi_scope.get(
|
||||
_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY, _SCOPE_MISSING
|
||||
)
|
||||
fastapi_scope[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = route_context
|
||||
try:
|
||||
match, child_scope = original_route.matches(scope)
|
||||
finally:
|
||||
_restore_fastapi_scope_key(
|
||||
scope,
|
||||
_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY,
|
||||
previous_context,
|
||||
)
|
||||
route = original_route
|
||||
else:
|
||||
match, child_scope = candidate.matches(scope)
|
||||
route = candidate.starlette_route or original_route
|
||||
else:
|
||||
route_context = None
|
||||
match, child_scope = candidate.matches(scope)
|
||||
route = candidate
|
||||
if match == Match.FULL:
|
||||
if full is None:
|
||||
full = (child_scope, route, route_context)
|
||||
elif match == Match.PARTIAL:
|
||||
if partial is None:
|
||||
partial = (child_scope, route, route_context)
|
||||
if full is not None:
|
||||
child_scope, route, route_context = full
|
||||
return Match.FULL, child_scope, route, route_context
|
||||
if partial is not None:
|
||||
child_scope, route, route_context = partial
|
||||
return Match.PARTIAL, child_scope, route, route_context
|
||||
return Match.NONE, {}, None, None
|
||||
|
||||
def route(
|
||||
self,
|
||||
path: str,
|
||||
|
||||
@@ -319,7 +319,6 @@ extend-exclude = [
|
||||
"docs/de/",
|
||||
"docs/en/data/",
|
||||
"docs/en/docs/img/",
|
||||
"docs/en/docs/release-notes.md",
|
||||
"docs/es/",
|
||||
"docs/fr/",
|
||||
"docs/ja/",
|
||||
@@ -331,6 +330,7 @@ extend-exclude = [
|
||||
"docs/uk/",
|
||||
"docs/zh/",
|
||||
"docs/zh-hant/",
|
||||
"docs/hi/",
|
||||
"htmlcov/",
|
||||
"scripts/general-llm-prompt.md",
|
||||
"scripts/tests/test_translation_fixer/test_complex_doc/",
|
||||
@@ -339,6 +339,16 @@ extend-exclude = [
|
||||
"uv.lock",
|
||||
]
|
||||
|
||||
[tool.typos.default]
|
||||
extend-ignore-re = [
|
||||
# GitHub usernames in @mentions
|
||||
"@[a-zA-Z0-9](?:-?[a-zA-Z0-9])*",
|
||||
# Quoted typo documented in a release note
|
||||
"'wll' to 'will'",
|
||||
# German article title in a release note
|
||||
"FastAPI Modul.",
|
||||
]
|
||||
|
||||
[tool.typos.default.extend-identifiers]
|
||||
alls = "alls"
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ SUPPORTED_LANGS = {
|
||||
"uk",
|
||||
"zh",
|
||||
"zh-hant",
|
||||
"hi",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -132,7 +132,7 @@ def translate_page(
|
||||
print(f"Found existing translation: {out_path}")
|
||||
old_translation = out_path.read_text(encoding="utf-8")
|
||||
print(f"Translating {en_path} to {language} ({language_name})")
|
||||
agent = Agent("openai:gpt-5")
|
||||
agent = Agent("openai-chat:gpt-5.5")
|
||||
|
||||
MAX_ATTEMPTS = 3
|
||||
additional_instructions = ""
|
||||
|
||||
858
tests/test_frontend.py
Normal file
858
tests/test_frontend.py
Normal file
@@ -0,0 +1,858 @@
|
||||
import errno
|
||||
import os
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
|
||||
import anyio
|
||||
import pytest
|
||||
from fastapi import APIRouter, FastAPI, HTTPException, Request, WebSocket
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.responses import PlainTextResponse, Response
|
||||
from starlette.routing import BaseRoute, Match, NoMatchFound, Route
|
||||
|
||||
|
||||
def write_file(path: Path, content: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content)
|
||||
|
||||
|
||||
def test_frontend_exact_prefix_path_serves_index(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app")
|
||||
app = FastAPI()
|
||||
app.frontend("/app", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/app")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "app"
|
||||
|
||||
|
||||
def test_apirouter_frontend_with_router_prefix_and_frontend_subpath(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "asset.txt", "asset")
|
||||
router = APIRouter(prefix="/internal")
|
||||
router.frontend("/ui", directory=dist)
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/prefix")
|
||||
|
||||
response = TestClient(app).get("/prefix/internal/ui/asset.txt")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "asset"
|
||||
|
||||
|
||||
def test_frontend_fallback_rejects_invalid_fallback(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
dist.mkdir()
|
||||
app = FastAPI()
|
||||
|
||||
with pytest.raises(AssertionError, match="fallback"):
|
||||
app.frontend("/", directory=dist, fallback="invalid") # type: ignore[arg-type] # ty: ignore[invalid-argument-type]
|
||||
|
||||
|
||||
def test_index_fallback_ignores_invalid_q_value(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get(
|
||||
"/dashboard/settings", headers={"accept": "text/html; q=wat"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "app shell"
|
||||
|
||||
|
||||
def test_frontend_static_files_lookup_errors(monkeypatch, tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
frontend_routes = app.router._frontend_routes
|
||||
assert frontend_routes is not None
|
||||
static_files = frontend_routes.routes[0].app
|
||||
|
||||
def raise_permission_error(path: str):
|
||||
raise PermissionError
|
||||
|
||||
monkeypatch.setattr(static_files, "lookup_path", raise_permission_error)
|
||||
response = TestClient(app).get("/asset.txt")
|
||||
assert response.status_code == 401
|
||||
|
||||
def raise_value_error(path: str):
|
||||
raise ValueError
|
||||
|
||||
monkeypatch.setattr(static_files, "lookup_path", raise_value_error)
|
||||
response = TestClient(app).get("/asset.txt")
|
||||
assert response.status_code == 404
|
||||
|
||||
def raise_name_too_long(path: str):
|
||||
raise OSError(errno.ENAMETOOLONG, "name too long")
|
||||
|
||||
monkeypatch.setattr(static_files, "lookup_path", raise_name_too_long)
|
||||
response = TestClient(app).get("/asset.txt")
|
||||
assert response.status_code == 404
|
||||
|
||||
def raise_os_error(path: str):
|
||||
raise OSError(5, "other")
|
||||
|
||||
monkeypatch.setattr(static_files, "lookup_path", raise_os_error)
|
||||
with pytest.raises(OSError):
|
||||
TestClient(app).get("/asset.txt")
|
||||
|
||||
|
||||
def test_frontend_route_group_helpers(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
route_group = app.router._frontend_routes
|
||||
assert route_group is not None
|
||||
|
||||
match, child_scope = route_group.matches({"type": "websocket", "path": "/"})
|
||||
assert match == Match.NONE
|
||||
assert child_scope == {}
|
||||
|
||||
with pytest.raises(StarletteHTTPException) as exc_info:
|
||||
anyio.run(
|
||||
route_group.with_prefix("/app").handle,
|
||||
{"type": "http", "path": "/missing", "method": "GET"},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
with pytest.raises(NoMatchFound):
|
||||
route_group.url_path_for("frontend")
|
||||
with pytest.raises(NoMatchFound):
|
||||
route_group.routes[0].url_path_for("frontend")
|
||||
|
||||
|
||||
def test_included_low_priority_routes_cache_is_reused():
|
||||
async def low_priority_endpoint(request: Request):
|
||||
return PlainTextResponse("low")
|
||||
|
||||
router = APIRouter()
|
||||
router._low_priority_routes.append(Route("/low", low_priority_endpoint))
|
||||
router._mark_routes_changed()
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/prefix")
|
||||
included_router = next(
|
||||
route
|
||||
for route in app.router.routes
|
||||
if hasattr(route, "effective_low_priority_routes")
|
||||
)
|
||||
|
||||
first = included_router.effective_low_priority_routes() # ty: ignore[call-non-callable]
|
||||
second = included_router.effective_low_priority_routes() # ty: ignore[call-non-callable]
|
||||
response = TestClient(app).get("/prefix/low")
|
||||
|
||||
assert first is second
|
||||
assert response.status_code == 200
|
||||
assert response.text == "low"
|
||||
|
||||
|
||||
def test_low_priority_api_route_handles_with_context():
|
||||
app = FastAPI()
|
||||
|
||||
async def endpoint(request: Request) -> Response:
|
||||
return PlainTextResponse(request.scope["path_params"]["item_id"])
|
||||
|
||||
route = app.router.route_class("/low/{item_id}", endpoint=endpoint, methods=["GET"])
|
||||
app.router._low_priority_routes.append(route)
|
||||
app.router._mark_routes_changed()
|
||||
|
||||
response = TestClient(app).get("/low/abc")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "abc"
|
||||
|
||||
|
||||
def test_included_low_priority_api_route_handles_with_context():
|
||||
router = APIRouter()
|
||||
|
||||
async def endpoint(request: Request) -> Response:
|
||||
return PlainTextResponse(request.scope["path_params"]["item_id"])
|
||||
|
||||
route = router.route_class("/low/{item_id}", endpoint=endpoint, methods=["GET"])
|
||||
router._low_priority_routes.append(route)
|
||||
router._mark_routes_changed()
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/prefix")
|
||||
|
||||
response = TestClient(app).get("/prefix/low/abc")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "abc"
|
||||
|
||||
|
||||
def test_normal_route_partial_match_returns_before_frontend(tmp_path: Path):
|
||||
class PartialRoute(BaseRoute):
|
||||
def matches(self, scope):
|
||||
return Match.PARTIAL, {}
|
||||
|
||||
async def handle(self, scope, receive, send):
|
||||
response = PlainTextResponse("partial", status_code=405)
|
||||
await response(scope, receive, send)
|
||||
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "frontend")
|
||||
app = FastAPI()
|
||||
app.router.routes.append(PartialRoute())
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/anything")
|
||||
|
||||
assert response.status_code == 405
|
||||
assert response.text == "partial"
|
||||
|
||||
|
||||
def test_normal_route_partial_match_wins_before_frontend(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "api", "frontend")
|
||||
app = FastAPI()
|
||||
|
||||
@app.get("/api")
|
||||
def read_api():
|
||||
return {"source": "api"}
|
||||
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
response = client.get("/api")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"source": "api"}
|
||||
|
||||
response = client.post("/api")
|
||||
assert response.status_code == 405
|
||||
|
||||
|
||||
def test_basic_file_serving(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "assets" / "app.js", "console.log('ok')")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/assets/app.js")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "console.log('ok')"
|
||||
assert "etag" in response.headers
|
||||
assert "last-modified" in response.headers
|
||||
|
||||
|
||||
def test_existing_api_route_wins_over_frontend(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "api" / "users", "frontend")
|
||||
app = FastAPI()
|
||||
|
||||
@app.get("/api/users")
|
||||
def read_users():
|
||||
return {"source": "api"}
|
||||
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/api/users")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"source": "api"}
|
||||
|
||||
|
||||
def test_api_route_404_is_not_replaced_by_frontend_fallback(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "frontend")
|
||||
app = FastAPI()
|
||||
|
||||
@app.get("/api/users")
|
||||
def read_users():
|
||||
raise HTTPException(status_code=404, detail="api missing")
|
||||
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get("/api/users", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "api missing"}
|
||||
|
||||
|
||||
def test_index_fallback_for_navigation_request(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get(
|
||||
"/dashboard/settings", headers={"accept": "text/html"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "app shell"
|
||||
|
||||
|
||||
def test_index_fallback_parses_accept_parameters(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get(
|
||||
"/dashboard/settings", headers={"accept": "text/html; q=0.8"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "app shell"
|
||||
|
||||
|
||||
def test_index_fallback_ignores_q_zero_accept(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get(
|
||||
"/dashboard/settings", headers={"accept": "text/html; q=0.0"}
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_index_fallback_respects_explicit_html_rejection_with_wildcard(
|
||||
tmp_path: Path,
|
||||
):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get(
|
||||
"/dashboard/settings",
|
||||
headers={"accept": "text/html; q=0, */*; q=1"},
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_index_fallback_respects_explicit_xhtml_rejection_with_wildcard(
|
||||
tmp_path: Path,
|
||||
):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get(
|
||||
"/dashboard/settings",
|
||||
headers={"accept": "application/xhtml+xml; q=0, */*; q=1"},
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "accept"),
|
||||
[
|
||||
("/assets/missing.js", "*/*"),
|
||||
("/assets/missing.css", "text/css"),
|
||||
("/assets/missing.png", "image/png"),
|
||||
("/api/missing", "application/json"),
|
||||
("/users/jane.doe", "text/html"),
|
||||
],
|
||||
)
|
||||
def test_index_fallback_does_not_handle_asset_like_or_non_html_requests(
|
||||
tmp_path: Path, path: str, accept: str
|
||||
):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get(path, headers={"accept": accept})
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.text != "app shell"
|
||||
|
||||
|
||||
def test_404_fallback_handles_missing_assets(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "404.html", "missing")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback="404.html")
|
||||
|
||||
response = TestClient(app).get("/assets/missing.js")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.text == "missing"
|
||||
|
||||
|
||||
def test_auto_fallback_prefers_404_over_index(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
write_file(dist / "404.html", "missing")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/dashboard", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.text == "missing"
|
||||
|
||||
|
||||
def test_auto_fallback_uses_index_when_404_is_missing(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/dashboard", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "app shell"
|
||||
|
||||
|
||||
def test_auto_fallback_returns_normal_404_without_fallback_files(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
dist.mkdir()
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/dashboard", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "Not Found"}
|
||||
|
||||
|
||||
def test_no_fallback_returns_normal_404(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app shell")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist, fallback=None)
|
||||
|
||||
response = TestClient(app).get("/dashboard", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "Not Found"}
|
||||
|
||||
|
||||
def test_directory_index_and_redirect(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "about" / "index.html", "about")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
client = TestClient(app)
|
||||
|
||||
redirect = client.get("/about", follow_redirects=False)
|
||||
response = client.get("/about/")
|
||||
|
||||
assert redirect.status_code == 307
|
||||
assert redirect.headers["location"] == "http://testserver/about/"
|
||||
assert response.status_code == 200
|
||||
assert response.text == "about"
|
||||
|
||||
|
||||
def test_path_validation_and_trailing_slash_normalization(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "asset.txt", "ok")
|
||||
app = FastAPI()
|
||||
|
||||
with pytest.raises(AssertionError):
|
||||
app.frontend("", directory=dist)
|
||||
with pytest.raises(AssertionError):
|
||||
app.frontend("app", directory=dist)
|
||||
|
||||
app.frontend("/app/", directory=dist)
|
||||
response = TestClient(app).get("/app/asset.txt")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "ok"
|
||||
|
||||
|
||||
def test_frontend_path_matching_uses_segment_boundaries(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app")
|
||||
app = FastAPI()
|
||||
app.frontend("/app", directory=dist, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get("/application", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_multiple_frontends_use_longest_matching_prefix(tmp_path: Path):
|
||||
site = tmp_path / "site"
|
||||
admin = tmp_path / "admin"
|
||||
write_file(site / "index.html", "site")
|
||||
write_file(admin / "index.html", "admin")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=site, fallback="index.html")
|
||||
app.frontend("/admin", directory=admin, fallback="index.html")
|
||||
|
||||
response = TestClient(app).get("/admin/settings", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "admin"
|
||||
|
||||
|
||||
def test_apirouter_frontend_uses_include_prefix(tmp_path: Path):
|
||||
dist = tmp_path / "admin"
|
||||
write_file(dist / "index.html", "admin")
|
||||
router = APIRouter()
|
||||
router.frontend("/", directory=dist, fallback="index.html")
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/admin")
|
||||
|
||||
response = TestClient(app).get("/admin/settings", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "admin"
|
||||
|
||||
|
||||
def test_global_priority_across_included_routers(tmp_path: Path):
|
||||
dist = tmp_path / "site"
|
||||
write_file(dist / "index.html", "site")
|
||||
site_router = APIRouter()
|
||||
site_router.frontend("/", directory=dist, fallback="index.html")
|
||||
api_router = APIRouter()
|
||||
|
||||
@api_router.get("/api/users")
|
||||
def read_users():
|
||||
return {"source": "api"}
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(site_router)
|
||||
app.include_router(api_router)
|
||||
|
||||
response = TestClient(app).get("/api/users", headers={"accept": "text/html"})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"source": "api"}
|
||||
|
||||
|
||||
def test_nested_apirouter_frontend_uses_all_include_prefixes(tmp_path: Path):
|
||||
dist = tmp_path / "admin"
|
||||
write_file(dist / "index.html", "admin")
|
||||
child_router = APIRouter()
|
||||
child_router.frontend("/", directory=dist, fallback="index.html")
|
||||
parent_router = APIRouter()
|
||||
parent_router.include_router(child_router, prefix="/child")
|
||||
app = FastAPI()
|
||||
app.include_router(parent_router, prefix="/parent")
|
||||
|
||||
response = TestClient(app).get(
|
||||
"/parent/child/settings", headers={"accept": "text/html"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "admin"
|
||||
|
||||
|
||||
def test_low_priority_cache_updates_after_route_added_to_included_router(
|
||||
tmp_path: Path,
|
||||
):
|
||||
dist = tmp_path / "site"
|
||||
write_file(dist / "index.html", "site")
|
||||
router = APIRouter()
|
||||
router.frontend("/", directory=dist, fallback="index.html")
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/app")
|
||||
client = TestClient(app)
|
||||
|
||||
frontend_response = client.get("/app/dashboard", headers={"accept": "text/html"})
|
||||
|
||||
@router.get("/dashboard")
|
||||
def read_dashboard():
|
||||
return {"source": "api"}
|
||||
|
||||
api_response = client.get("/app/dashboard", headers={"accept": "text/html"})
|
||||
|
||||
assert frontend_response.status_code == 200
|
||||
assert frontend_response.text == "site"
|
||||
assert api_response.status_code == 200
|
||||
assert api_response.json() == {"source": "api"}
|
||||
|
||||
|
||||
def test_normal_route_slash_redirect_wins_before_frontend_redirect(tmp_path: Path):
|
||||
dist = tmp_path / "site"
|
||||
write_file(dist / "api" / "index.html", "frontend")
|
||||
app = FastAPI()
|
||||
|
||||
@app.get("/api/")
|
||||
def read_api():
|
||||
return {"source": "api"}
|
||||
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/api", follow_redirects=False)
|
||||
|
||||
assert response.status_code == 307
|
||||
assert response.headers["location"] == "http://testserver/api/"
|
||||
|
||||
followed = TestClient(app).get("/api/")
|
||||
assert followed.status_code == 200
|
||||
assert followed.json() == {"source": "api"}
|
||||
|
||||
|
||||
def test_frontend_respects_root_path(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "assets" / "app.js", "console.log('ok')")
|
||||
app = FastAPI()
|
||||
app.frontend("/app", directory=dist)
|
||||
|
||||
response = TestClient(app, root_path="/proxy").get("/app/assets/app.js")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "console.log('ok')"
|
||||
|
||||
|
||||
def test_websocket_route_wins_over_frontend(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "ws", "frontend")
|
||||
app = FastAPI()
|
||||
|
||||
@app.websocket("/ws")
|
||||
async def websocket_endpoint(websocket: WebSocket):
|
||||
await websocket.accept()
|
||||
await websocket.send_text("websocket")
|
||||
await websocket.close()
|
||||
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
with TestClient(app).websocket_connect("/ws") as websocket:
|
||||
data = websocket.receive_text()
|
||||
|
||||
assert data == "websocket"
|
||||
|
||||
|
||||
def test_head_requests_work(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "asset.txt", "ok")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).head("/asset.txt")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == ""
|
||||
assert response.headers["content-length"] == "2"
|
||||
|
||||
|
||||
def test_unsupported_methods_return_405(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "asset.txt", "ok")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).post("/asset.txt")
|
||||
|
||||
assert response.status_code == 405
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
[
|
||||
"/../secret.txt",
|
||||
"/%2e%2e/secret.txt",
|
||||
"/..%2fsecret.txt",
|
||||
"/%5c..%5csecret.txt",
|
||||
"/..%5csecret.txt",
|
||||
],
|
||||
)
|
||||
def test_path_traversal_cannot_escape_directory(tmp_path: Path, path: str):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app")
|
||||
write_file(tmp_path / "secret.txt", "secret")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get(path)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.text != "secret"
|
||||
|
||||
|
||||
def test_symlink_outside_directory_is_not_served(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
dist.mkdir()
|
||||
outside = tmp_path / "secret.txt"
|
||||
outside.write_text("secret")
|
||||
link = dist / "secret.txt"
|
||||
try:
|
||||
os.symlink(outside, link)
|
||||
except (OSError, NotImplementedError): # pragma: no cover
|
||||
pytest.skip("symlinks are not supported")
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=dist)
|
||||
|
||||
response = TestClient(app).get("/secret.txt")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.text != "secret"
|
||||
|
||||
|
||||
def test_check_dir_true_fails_early_for_missing_directory(monkeypatch, tmp_path: Path):
|
||||
app = FastAPI()
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
with pytest.raises(RuntimeError, match="does not exist") as exc_info:
|
||||
app.frontend("/", directory="missing")
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "'missing'" in message
|
||||
assert str(tmp_path / "missing") in message
|
||||
|
||||
|
||||
def test_check_dir_false_allows_missing_directory_and_fails_on_request(tmp_path: Path):
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory=tmp_path / "missing", check_dir=False)
|
||||
|
||||
with pytest.raises(RuntimeError, match="does not exist"):
|
||||
TestClient(app).get("/asset.txt")
|
||||
|
||||
|
||||
def test_explicit_fallback_files_fail_clearly_when_missing(monkeypatch, tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
dist.mkdir()
|
||||
monkeypatch.chdir(tmp_path)
|
||||
app = FastAPI()
|
||||
|
||||
with pytest.raises(RuntimeError, match="index.html") as exc_info:
|
||||
app.frontend("/", directory="dist", fallback="index.html")
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "directory 'dist'" in message
|
||||
assert str(dist) in message
|
||||
|
||||
app = FastAPI()
|
||||
app.frontend("/", directory="dist", fallback="404.html", check_dir=False)
|
||||
|
||||
with pytest.raises(RuntimeError, match="404.html") as exc_info:
|
||||
TestClient(app).get("/missing.js")
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "directory 'dist'" in message
|
||||
assert str(dist) in message
|
||||
|
||||
|
||||
def test_frontend_routes_are_not_in_openapi(tmp_path: Path):
|
||||
dist = tmp_path / "dist"
|
||||
write_file(dist / "index.html", "app")
|
||||
app = FastAPI()
|
||||
|
||||
@app.get("/api")
|
||||
def read_api():
|
||||
return {"ok": True}
|
||||
|
||||
app.frontend("/", directory=dist, fallback="index.html")
|
||||
|
||||
schema = TestClient(app).get("/openapi.json").json()
|
||||
|
||||
assert set(schema["paths"]) == {"/api"}
|
||||
|
||||
response = TestClient(app).get("/api")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"ok": True}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("example", "files", "path", "status_code", "body"),
|
||||
[
|
||||
(
|
||||
"tutorial001_py310.py",
|
||||
{"asset.txt": "asset"},
|
||||
"/asset.txt",
|
||||
200,
|
||||
"asset",
|
||||
),
|
||||
(
|
||||
"tutorial002_py310.py",
|
||||
{"index.html": "index"},
|
||||
"/dashboard",
|
||||
200,
|
||||
"index",
|
||||
),
|
||||
(
|
||||
"tutorial003_py310.py",
|
||||
{"404.html": "missing"},
|
||||
"/missing",
|
||||
404,
|
||||
"missing",
|
||||
),
|
||||
(
|
||||
"tutorial004_py310.py",
|
||||
{"index.html": "index"},
|
||||
"/app/dashboard",
|
||||
200,
|
||||
"index",
|
||||
),
|
||||
(
|
||||
"tutorial005_py310.py",
|
||||
{"index.html": "index"},
|
||||
"/dashboard",
|
||||
404,
|
||||
'{"detail":"Not Found"}',
|
||||
),
|
||||
(
|
||||
"tutorial006_py310.py",
|
||||
{"asset.txt": "asset"},
|
||||
"/asset.txt",
|
||||
200,
|
||||
"asset",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_docs_frontend_examples(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
example: str,
|
||||
files: dict[str, str],
|
||||
path: str,
|
||||
status_code: int,
|
||||
body: str,
|
||||
):
|
||||
dist = tmp_path / "dist"
|
||||
for file, content in files.items():
|
||||
write_file(dist / file, content)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
namespace = runpy.run_path(
|
||||
str(Path(__file__).parents[1] / "docs_src" / "frontend" / example)
|
||||
)
|
||||
|
||||
app = namespace["app"]
|
||||
assert isinstance(app, FastAPI)
|
||||
response = TestClient(app).get(path, headers={"accept": "text/html"})
|
||||
assert response.status_code == status_code
|
||||
assert response.text == body
|
||||
|
||||
|
||||
def test_low_priority_routes_can_store_non_frontend_routes():
|
||||
async def low_priority_endpoint(request):
|
||||
return PlainTextResponse("low")
|
||||
|
||||
app = FastAPI()
|
||||
app.router._low_priority_routes.append(Route("/low", low_priority_endpoint))
|
||||
app.router._mark_routes_changed()
|
||||
|
||||
response = TestClient(app).get("/low")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "low"
|
||||
|
||||
|
||||
def test_included_low_priority_routes_can_store_non_frontend_routes():
|
||||
async def low_priority_endpoint(request):
|
||||
return PlainTextResponse("low")
|
||||
|
||||
router = APIRouter()
|
||||
router._low_priority_routes.append(Route("/low", low_priority_endpoint))
|
||||
router._mark_routes_changed()
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/prefix")
|
||||
|
||||
response = TestClient(app).get("/prefix/low")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.text == "low"
|
||||
Reference in New Issue
Block a user