diff --git "a/data/eval_cache.json" "b/data/eval_cache.json" --- "a/data/eval_cache.json" +++ "b/data/eval_cache.json" @@ -189,5 +189,159 @@ "d2137628f12fc5e5": "You can use FastAPI with the Django ORM by running your FastAPI application with a WSGI server that supports Django, or by using a third-party library that provides integration between FastAPI and Django.\n\nHowever, I couldn't find an official guide or a simple example in the provided context chunks. But I can tell you that it is possible to integrate FastAPI with Django.\n\nFastAPI is an ASGI framework, while Django is a WSGI framework. You can use a library like [Daphne](https://github.com/django/daphne) which is an ASGI server built for Django Channels, or [Hypercorn](https://hypercorn.readthedocs.io/) which is an ASGI server compatible with HTTP/2 and Trio.\n\nTo integrate FastAPI with the Django ORM, you would typically:\n- Run your Django application with the Django development server or a WSGI server like Gunicorn.\n- Run your FastAPI application with an ASGI server like Uvicorn.\n- Use a database like PostgreSQL that both Django and FastAPI can connect to.\n\nHere is an example of how you might structure your project:\n```python\n# myproject/settings.py (Django)\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'mydatabase',\n 'USER': 'mydatabaseuser',\n 'PASSWORD': 'mypassword',\n 'HOST': '127.0.0.1',\n 'PORT': '5432',\n }\n}\n\n# myapp/main.py (FastAPI)\nfrom fastapi import FastAPI\nfrom django.core.management import call_command\nimport os\n\n# Configure Django\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')\ncall_command('makemigrations')\ncall_command('migrate')\n\nfrom myapp.models import MyModel\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n items = MyModel.objects.all()\n return [{\"id\": item.id, \"name\": item.name} for item in items]\n```\nKeep in mind that this is a simplified example and does not cover error handling, database connections and other important aspects.\n\nFor more information, you can check [docs/en/docs/deployment/manually.md][1] and [docs/en/docs/advanced/wsgi.md][4].", "7d309358c1c04b1d": "I couldn't find this in the indexed codebase.", "9b649898daa89d96": "I couldn't find this in the indexed codebase.", - "5451166579a6804a": "I couldn't find this in the indexed codebase." + "5451166579a6804a": "I couldn't find this in the indexed codebase.", + "c6eefa1e892e9de4": "You can set a custom status code for an endpoint in several ways.\n\n## Using the `status_code` Parameter\n\nYou can pass the `status_code` parameter to any of the path operations, such as `@app.get()`, `@app.post()`, etc. This parameter receives a number with the HTTP status code or an `IntEnum`, such as Python's [`http.HTTPStatus`].\n\nExample:\n```python\nfrom fastapi import FastAPI, status\n\napp = FastAPI()\n\n@app.get(status_code=200)\nasync def read_items():\n return [{\"item\": \"Item 1\"}]\n```\n## Returning a `Response` Directly\n\nYou can return a `Response` directly, such as a `JSONResponse`, and set the status code directly.\n\nExample:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get()\nasync def read_items():\n return JSONResponse(content=[{\"item\": \"Item 1\"}], status_code=201)\n```\n## Using `status` Constants\n\nYou can use the shortcut constants in `status` to set the status code.\n\nExample:\n```python\nfrom fastapi import FastAPI, status\n\napp = FastAPI()\n\n@app.get(status_code=status.HTTP_200_OK)\nasync def read_items():\n return [{\"item\": \"Item 1\"}]\n```\nNote that you can also use `from starlette import status` or `from starlette.responses import JSONResponse`, as FastAPI provides the same `starlette.status` and `starlette.responses` as `fastapi.status` and `fastapi.responses` for convenience. [2][1]", + "e180a83e38fc75af": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "200dee9261b382fb": "To receive an uploaded file in an endpoint, you can define a *path operation function* parameter to be of the type `UploadFile`. \n\nYou can import `UploadFile` directly from `fastapi`:\n```python\nfrom fastapi import UploadFile\n```\nThen, use it as a parameter in your endpoint function. \n\nAdditionally, to receive uploaded files, you need to install `python-multipart` and make sure to create a virtual environment, activate it, and then install it.\n\nYou can also use `File` to declare files to be uploaded in the request, sent as form data. \n\nHere is an example of how to define file parameters:\n```python\nfrom fastapi import File, UploadFile\n```\nCreate file parameters the same way you would for `Body` or `Form`. \n\nRemember that `File` is a class that inherits directly from `Form`. \n\nYou can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON.\n\nFor more details, you can check [2] for `UploadFile` class, [1] and [5] for `File` parameters, and [4] for defining `File` and `Form` parameters. \n\nAlso, recall that you can use `File`, `bytes`, and `UploadFile` to declare files to be uploaded in the request, sent as form data [3].", + "6b4ba6a854c559d0": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "46f50db46e831c5b": "You can define background tasks to be run *after* returning a response using the `BackgroundTasks` class from FastAPI. \n\nHere's an example of how to use it:\n\n```python\nfrom fastapi import FastAPI, BackgroundTasks\n\napp = FastAPI()\n\ndef task1():\n print(\"Task 1 is running in the background\")\n\n@app.get(\"/items/\")\nasync def read_items(background_tasks: BackgroundTasks):\n background_tasks.add_task(task1)\n return {\"message\": \"Item read\"}\n```\n\nIn this example, `task1` will be executed in the background after the response is sent.\n\nNote that background tasks only run if a 2xx response is sent back. If you raise an `HTTPException`, the background tasks will not be executed [3].\n\nIf you want to record something when raising an `HTTPException` in a background task, you can create a custom exception handler. However, for now, you can manually log or record the information.\n\nAlso, be aware that if you return a `Response` object with its own `background` attribute set, the injected background tasks will be silently discarded. In such cases, you should consider emitting a warning or error to notify the developer [5]. \n\nYou can find more information about background tasks in the FastAPI documentation [1][2]. \n\nHere's a more detailed example from the documentation:\n\n```python\nfrom fastapi import BackgroundTasks, FastAPI\n\napp = FastAPI()\n\ndef write_notification(email: str, message=\"\"):\n with open(\"log.txt\", mode=\"w\") as email_file:\n content = f\"notification for {email}: {message}\"\n email_file.write(content)\n\n@app.post(\"/send-notification/{email}\")\nasync def send_notification(email: str, background_tasks: BackgroundTasks):\n background_tasks.add_task(write_notification, email, message=\"some notification\")\n return {\"message\": \"Notification sent in the background\"}\n```", + "ac118d817e50b499": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "d6809731322db80a": "To enable CORS (Cross-Origin Resource Sharing) for your frontend to call the API, you need to configure your backend to allow cross-origin requests. Here's a step-by-step guide:\n\n## Steps to Enable CORS\n\n1. **Understand CORS**: CORS is a security feature implemented in web browsers to prevent web pages from making requests to a different origin (domain, protocol, or port) than the one the web page was loaded from.\n2. **Configure CORSMiddleware**: In your FastAPI application, import `CORSMiddleware` and create a list of allowed origins. Add it as a middleware to your FastAPI application.\n3. **Specify Allowed Origins**: Specify the origins that should be permitted to make cross-origin requests using the `allow_origins` parameter. For example, `['https://example.org', 'https://www.example.org']`. You can use `['*']` to allow any origin.\n4. **Configure Other Settings**: You can also specify other settings, such as:\n\t* `allow_methods`: A list of HTTP methods that should be allowed for cross-origin requests. Defaults to `['GET']`. You can use `['*']` to allow all standard methods.\n\t* `allow_headers`: A list of HTTP request headers that should be supported for cross-origin requests. Defaults to `[]`. You can use `['*']` to allow all headers.\n\t* `allow_credentials`: Indicate that cookies should be supported for cross-origin requests. Defaults to `False`.\n\n## Example Code\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\n\norigins = [\n \"http://localhost:8080\",\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n```\n\n## More Information\n\nFor more information about CORS, check the [Mozilla CORS documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). [3]\n\n## Use CORSMiddleware\n\nYou can also use `CORSMiddleware` from `starlette.middleware.cors`. FastAPI provides several middlewares in `fastapi.middleware` as a convenience for developers, but most of the available middlewares come directly from Starlette. [2]", + "9bce3a8d7ec66bfb": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "9ca0370c22ee52c1": "You can declare optional query parameters with default values by setting their default to a specific value, such as `None`, or any other type of value.\n\nFor example, you can declare an optional query parameter `q` with a default value of `None` like this:\n```python\nq: str | None = None\n```\nThis way, the `q` query parameter is optional and will be `None` by default if not provided.\n\nYou can also use other default values, such as strings, integers, etc. For example:\n```python\nq: str = \"fixedquery\"\n```\nThis way, the `q` query parameter has a default value of `\"fixedquery\"` and is optional.\n\nAdditionally, you can use `Query` parameters with validations and metadata, and make them required or optional by declaring or not declaring a default value [2][5].\n\nFor example, you can declare a required query parameter `q` with a `min_length` validation like this:\n```python\nq: Annotated[str, Query(min_length=3)]\n```\nAnd you can declare an optional query parameter with a default value like this:\n```python\nq: Annotated[str | None, Query(min_length=3)] = None\n```", + "f4657c25703e275d": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "168ef102b375a6e9": "You can declare the type of a path parameter in the function using standard Python type annotations. For example, to declare a path parameter `item_id` with type `int`, you can do:\n\n{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}\n\nThis will give you editor support inside of your function, with error checks, completion, etc. [1]", + "5e72317f90198fda": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "b757c1ae84e13924": "To receive a JSON request body using a Pydantic model, you need to declare a Pydantic model with the fields you want to receive and then use it as a parameter in your route function. \n\nYou can declare a Pydantic model by importing `BaseModel` from `pydantic` [5] and then creating a class that inherits from `BaseModel`. \n\nFor example, you can declare a model with `bytes` fields and use `val_json_bytes` in the model config to tell it to use base64 to validate input JSON data [1]. \n\nYou can also use `bytes` fields with `ser_json_bytes` in the model config for output data, and Pydantic will serialize the bytes as base64 when generating the JSON response [2].\n\nHere's an example of how you can declare a Pydantic model:\n\n```python\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n description: str\n data: bytes\n```\n\nThen, you can use this model as a parameter in your route function:\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass Item(BaseModel):\n description: str\n data: bytes\n\n@app.post(\"/items/\")\nasync def create_item(item: Item):\n return item\n```\n\nIn this example, FastAPI will extract the data from the request body, validate it using the Pydantic model, and then pass it to your route function. \n\nYou can send a request with a JSON body like this:\n\n```json\n{\n \"description\": \"Some data\",\n \"data\": \"aGVsbG8=\"\n}\n```\n\nAnd FastAPI will decode the base64 string and give you the original bytes in the `data` field of the model. \n\nYou can also declare a body as a `dict` with keys of some type and values of some other type [3]. \n\nAdditionally, you can use Pydantic models for forms by declaring a Pydantic model with the fields you want to receive as form fields and then declaring the parameter as `Form` [4].", + "749941de3a393cb4": "```json\n{\n \"faithful\": false,\n \"correct\": true\n}\n```", + "5c9cede9f013ec43": "To receive form data instead of JSON, you can use `Form` in your FastAPI application. \n\nFirst, ensure you have `python-multipart` installed. You can install it using pip:\n\n```console\n$ pip install python-multipart\n```\n\nThen, define your form parameters using `Form`:\n\n## Define `Form` parameters \n\nCreate form parameters the same way you would for `Body` or `Query`:\n\n```python\nfrom fastapi import FastAPI, Form\n\napp = FastAPI()\n\n@app.post(\"/login/\")\ndef login(username: str = Form(...), password: str = Form(...)):\n return {\"username\": username}\n```\n\nIn this example, `username` and `password` are form fields.\n\n## Technical Details\n\nData from forms is normally encoded using the \"media type\" `application/x-www-form-urlencoded`.\n\n## Note\n`Form` is a class that inherits directly from `Body`.\n\n## Tip\nTo declare form bodies, you need to use `Form` explicitly, because without it the parameters would be interpreted as query parameters or body (JSON) parameters.\n\n## Warning\nYou can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`. This is not a limitation of **FastAPI**, it's part of the HTTP protocol. [1][3]", + "75f927981495c173": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "ccde1d23b32380ae": "To return a custom error response with a specific status code and message, you can return a `Response` object directly, such as a `JSONResponse`, and set the status code and content accordingly.\n\nYou can use the `JSONResponse` object from `fastapi.responses` to return a JSON response with a custom status code. For example:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n # Custom error response with status code 400 and message\n return JSONResponse(content={\"error\": \"Invalid request\"}, status_code=400)\n```\n\nAlternatively, you can use the `status_code` parameter in a path operation decorator to specify the status code, and return a response object:\n\n```python\nfrom fastapi import FastAPI, HTTPException\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n # Custom error response with status code 400 and message\n raise HTTPException(status_code=400, detail=\"Invalid request\")\n```\n\nYou can also return a custom response object with a specific status code and message:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import Response\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n # Custom response with status code 201 and message\n return Response(content={\"message\": \"Item created\"}, media_type=\"application/json\", status_code=201)\n```\n\nMake sure to handle the response content and status code according to your specific use case [1][2][4]. \n\nAlso, note that you can use `IntEnum` such as Python's `http.HTTPStatus` for status code [2]. \n\nFastAPI will use the default status code or the one you set in your path operation, and return responses using a `JSONResponse` by default [3]. \n\nFor more information on HTTP status codes, you can refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) [5].", + "5be45cff2d435572": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "df7ae647758eafe1": "You can use the `response_model` parameter in FastAPI to control which fields are returned in the response. This is particularly useful when you want to filter data to expose only public fields and avoid exposing sensitive information.\n\nHere are some ways to use `response_model`:\n\n### Using `response_model` with a different return type\n\nIf the return type is not the same as the type that you want to use to validate, filter, or serialize, use the `response_model` parameter on the decorator.\n\n```python\nfrom typing import Any\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n\n@app.get(\"/items/me\", response_model=Item)\nasync def get_item() -> Any:\n return {\"name\": \"Foo\", \"description\": \"A very nice Item\"}\n```\n\n### Using `response_model` to filter out sensitive information\n\nYou can use `response_model` to filter out sensitive information by defining a separate model for the response.\n\n```python\nfrom typing import Any\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass InternalItem(BaseModel):\n name: str\n description: str | None = None\n secret_key: str\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n\n@app.get(\"/items/me\", response_model=Item)\nasync def get_item() -> Any:\n item = InternalItem(\n name=\"Foo\", description=\"A very nice Item\", secret_key=\"supersecret\"\n )\n return item\n```\n\n### Using `response_model_exclude_unset` to exclude default values\n\nYou can use the `response_model_exclude_unset` parameter to exclude default values from the response.\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float = 10.5\n tags: list[str] = []\n\n@app.get(\"/items/me\", response_model=Item, response_model_exclude_unset=True)\nasync def get_item():\n item = Item(\n name=\"Foo\", description=\"A very nice Item\", price=50.2, tax=20.2, tags=[]\n )\n return item\n```\n\nBy using `response_model` and its associated parameters, you can control which fields are returned in the response and ensure that sensitive information is not exposed. [2][5]", + "b44b2060a52a5664": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "abf921343272e70e": "You can serve static files like images or CSS using the `StaticFiles` class in FastAPI. \n\nHere's how to do it [3]:\n- Use `StaticFiles` to serve static files automatically from a directory.\n\nHere's an example of how to use it [1]:\n- Import `StaticFiles` directly from `fastapi.staticfiles`.\n- Mount a `StaticFiles()` instance in a specific path.\n\nYou can also use `url_for()` inside of a template with the `StaticFiles` you mounted with the `name=\"static\"` [2].\n\nFor example, you can serve static files from a directory named `static` [4]:\n- Create a directory named `static` in your project directory.\n- Download the necessary static files (like `swagger-ui-bundle.js`, `swagger-ui.css`, and `redoc.standalone.js`) and put them in the `static` directory.\n- Serve the static files by mounting a `StaticFiles()` instance in a specific path.\n\nHere's a code example [4]:\n```python\nfrom fastapi.staticfiles import StaticFiles\n\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n```", + "5d11ef4b822e7b89": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "c2d8fd0902f9d594": "To write tests for your FastAPI endpoints, you can use the `TestClient` provided by Starlette, which is the foundation of FastAPI. This allows you to simulate HTTP requests to your application and verify the responses.\n\nHere's a basic example of how to test a FastAPI endpoint:\n\n```python\nfrom fastapi.testclient import TestClient\nfrom .main import app\n\nclient = TestClient(app)\n\ndef test_read_root():\n response = client.get(\"/\")\n assert response.status_code == 200\n assert response.json() == {\"Hello\": \"World\"}\n```\n\nIn this example, we're testing the root endpoint (`\"/\"`) of our FastAPI application. We use the `TestClient` to send a GET request to this endpoint and then assert that the response status code is 200 and the response JSON is as expected.\n\nYou can also use asynchronous tests with FastAPI. To do this, you'll need to use an asynchronous test client and write your tests as asynchronous functions:\n\n```python\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom .main import app\n\n@pytest.fixture\ndef client():\n return TestClient(app)\n\n@pytest.mark.asyncio\nasync def test_read_root(client):\n response = client.get(\"/\")\n assert response.status_code == 200\n assert response.json() == {\"Hello\": \"World\"}\n```\n\nHowever, to truly leverage asynchronous testing, you would typically use an async/await syntax within your test functions and utilize libraries that support asynchronous operations, such as databases.\n\nFastAPI's documentation provides more detailed information on [async tests](https://fastapi.tiangolo.com/docs/advanced/async-tests/) and [testing in general](https://fastapi.tiangolo.com/docs/tutorial/testing/).\n\nFor more complex scenarios, such as testing database interactions, you might want to look into using Pytest's fixtures and parametrize features to simplify and organize your tests.\n\n### Key Points:\n- Use `TestClient` for synchronous tests.\n- Leverage async/await for asynchronous tests, especially when interacting with async operations like database queries.\n- Pytest integrates well with FastAPI for writing and running tests.\n\n### Example Use Case:\n\nSuppose you have a simple FastAPI app:\n\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n```\n\nYou can test it synchronously:\n\n```python\nfrom fastapi.testclient import TestClient\nfrom .main import app\n\nclient = TestClient(app)\n\ndef test_read_root():\n response = client.get(\"/\")\n assert response.status_code == 200\n assert response.json() == {\"Hello\": \"World\"}\n```", + "99084bfb61afe135": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "5e82d774a45c4182": "To use WebSockets in FastAPI, you can follow these steps:\n\n## Step 1: Create a WebSocket Endpoint\n\nYou can create a WebSocket endpoint using the `@app.websocket()` decorator. For example:\n```python\nfrom fastapi import FastAPI, WebSocket\n\napp = FastAPI()\n\n@app.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n while True:\n data = await websocket.receive_text()\n await websocket.send_text(f\"Message text was: {data}\")\n```\n## Step 2: Run the Application\n\nTo run the application, use the `fastapi dev` command:\n```console\n$ fastapi dev\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n## Step 3: Test the WebSocket Endpoint\n\nOpen your browser at [http://127.0.0.1:8000](http://127.0.0.1:8000) and test the WebSocket endpoint.\n\n## Technical Details\n\n* You can import `WebSocket` directly from `fastapi` or `starlette.websockets`.\n* FastAPI provides the same `WebSocket` directly as a convenience for developers, but it comes directly from Starlette [3].\n\n## Additional Information\n\n* You can define dependencies for WebSockets using the `dependencies` parameter [4].\n* You can read more about using WebSockets in FastAPI in the [FastAPI documentation](https://fastapi.tiangolo.com/advanced/websockets/) [1].", + "07a3c9ebb1dc67d2": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "5a1b983f3464fc9a": "You can set a cookie in a response in several ways.\n\n### Using a `Response` parameter\n\nYou can declare a parameter of type `Response` in your *path operation function*. Then, you can set cookies in that *temporary* response object [2].\n\n```python\nfrom fastapi import FastAPI, Response\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items(response: Response):\n response.set_cookie(\"cookie_name\", \"cookie_value\")\n return [{\"item\": \"Item 1\"}]\n```\n\n### Returning a `Response` directly\n\nYou can create a response as described in [Return a Response Directly](response-directly.md), then set cookies in it, and return it [1].\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n response = JSONResponse(content=[{\"item\": \"Item 1\"}], media_type=\"application/json\")\n response.set_cookie(\"cookie_name\", \"cookie_value\")\n return response\n```\n\n### Using `starlette.responses`\n\nYou can also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse` [1].\n\n```python\nfrom fastapi import FastAPI\nfrom starlette.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n response = JSONResponse(content=[{\"item\": \"Item 1\"}], media_type=\"application/json\")\n response.set_cookie(\"cookie_name\", \"cookie_value\")\n return response\n```\n\nFor more information on available parameters and options, check the [documentation in Starlette](https://www.starlette.dev/responses/#set-cookie).", + "6a66b004cbed8274": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "66b90dd63d6d2903": "You can add custom headers to a response in several ways.\n\n## Using a Direct Response\n\nWhen returning a `Response` directly, you can pass the headers as an additional parameter [1].\n\n## Custom Headers\n\nFor custom proprietary headers, use the `X-` prefix. However, for client-side visibility in browsers, add them to CORS configurations using `expose_headers` [2].\n\n## Error Handling\n\nYou can also add custom headers to HTTP errors for advanced scenarios [3].\n\n## Returning a Custom Response\n\nWhen returning a custom response, such as XML, you can put the content in a string, add it to a `Response`, and return it [4].\n\n## Using Response Class\n\nYou can declare a response class in the path operation decorator using `response_class` and put the contents inside that response [5].\n\nHere is an example of adding custom headers when returning a direct response:\n\n```python\nfrom fastapi import FastAPI, Response\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n headers = {\"X-Custom-Header\": \"Custom Value\"}\n return Response(content=\"Item content\", media_type=\"text/plain\", headers=headers)\n```", + "3b09d675114e0c3f": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "e58a1d60b0a8ba32": "To implement JWT token authentication, you need to follow these steps:\n\n## Step 1: Install Required Modules and Generate a Secret Key\nInstall the required modules and generate a random secret key that will be used to sign the JWT tokens. You can generate a secure random secret key using the command:\n```console\n$ openssl rand -hex 32\n```\n## Step 2: Define Variables and Models\nDefine variables such as `SECRET_KEY`, `ALGORITHM`, and `ACCESS_TOKEN_EXPIRE_MINUTES`. Create a Pydantic Model that will be used in the token endpoint for the response.\n\n## Step 3: Create a Utility Function to Generate a New Access Token\nCreate a utility function to generate a new access token.\n\n## Step 4: Update the `/token` Path Operation\nUpdate the `/token` path operation to create a real JWT access token and return it.\n\n## Step 5: Handle JWT Tokens\nHandle JWT tokens by verifying their signature and checking their expiration.\n\n## Step 6: Use the JWT Token for Authentication\nUse the JWT token for authentication by including it in the `Authorization` header with the value `Bearer `.\n\n## Example Use Case\nFor example, you can use the following credentials to test the authentication:\n- Username: `johndoe`\n- Password: `secret`\n\nAfter authenticating, you will receive a JWT token that you can use to access protected endpoints.\n\n## Technical Details\nNote that the JWT specification includes a key `sub` with the subject of the token, which can be used to identify the user. The `sub` key should have a unique identifier across the entire application, and it should be a string.\n\nYou can find more information about JWT tokens and how they work at [https://jwt.io](https://jwt.io/). \n\nReferences: \n- [2] for an overview of OAuth2 with Password (and hashing), Bearer with JWT tokens.\n- [3] for details on handling JWT tokens.\n- [4] for information about JWT.\n- [5] for updating the `/token` path operation.\n- [1] for an example of using the authentication flow.", + "800ada7ca2cacd93": "```json\n{\n \"faithful\": false,\n \"correct\": false\n}\n```", + "5444a2e3d5a80f2c": "FastAPI's dependency injection system is designed to be simple to use and allow for easy integration with other components. It allows developers to declare dependencies for their path operation functions, and FastAPI will take care of providing those dependencies.\n\nIn essence, dependency injection in FastAPI means that a path operation function can declare things it requires to work, and FastAPI will take care of providing them. This is useful for shared logic, database connections, security, authentication, and more, while minimizing code repetition.\n\nHere's a high-level overview of how it works:\n\n* A dependency is a function that can take the same parameters as a path operation function.\n* A path operation function can declare a dependency using the `Depends` annotation.\n* FastAPI will then execute the dependency function and provide its result to the path operation function.\n\nFor example, consider a simple dependency function that takes query parameters and returns a dictionary:\n\n```python\ndef get_query(q: str | None = None, skip: int = 0, limit: int = 100):\n return {\"q\": q, \"skip\": skip, \"limit\": limit}\n```\n\nYou can then declare this dependency for a path operation function like this:\n\n```python\n@app.get(\"/items/\")\nasync def read_items(dependant: dict = Depends(get_query)):\n return dependant\n```\n\nIn this case, FastAPI will execute the `get_query` function and provide its result to the `read_items` function.\n\nFastAPI also provides guidelines for using dependencies effectively. For instance, it's recommended to avoid creating class dependencies when possible and instead create regular function dependencies that return class instances.\n\nHere's an example of how to create a function dependency that returns a class instance:\n\n```python\n@dataclass\nclass DatabasePaginator:\n offset: int = 0\n limit: int = 100\n q: str | None = None\n\ndef get_db_paginator(offset: int = 0, limit: int = 100, q: str | None = None):\n return DatabasePaginator(offset=offset, limit=limit, q=q)\n\nPaginatorDep = Annotated[DatabasePaginator, Depends(get_db_paginator)]\n\n@app.get(\"/items/\")\nasync def read_items(paginator: PaginatorDep):\n return paginator.get_page()\n```\n\nBy following these guidelines and using FastAPI's dependency injection system effectively, developers can write clean, maintainable, and scalable code [1][2][5].", + "0d1a3a12440c2dfb": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "205af392aec08b89": "`jsonable_encoder()` is a function provided by **FastAPI** that converts a data type, such as a Pydantic model, to a JSON-compatible format, like a `dict` or `list`. You need it in cases where you have to store or return data that isn't inherently compatible with JSON, such as `datetime` objects or Pydantic models.\n\nHere are some scenarios where you might need to use `jsonable_encoder()`:\n\n* When you need to store data in a database that only accepts JSON-compatible data.\n* When you're working with a Pydantic model and need to convert it to a `dict` or other JSON-compatible format.\n* When you're creating a custom response and need to ensure the data is in a JSON-compatible format.\n\nFor example, if you have a Pydantic model with a `datetime` field, you can use `jsonable_encoder()` to convert it to a `dict` with the `datetime` field converted to a string in ISO format.\n\nThe function takes an object as input and returns a JSON-compatible version of that object. It doesn't return a large string containing the data in JSON format; instead, it returns a Python standard data structure (like a `dict`) with values and sub-values that are all compatible with JSON.\n\nHere's a code example demonstrating its usage:\n\n```python\nfrom fastapi.encoders import jsonable_encoder\nfrom datetime import datetime\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n name: str\n created_at: datetime\n\nitem = Item(name=\"Example Item\", created_at=datetime.now())\n\n# Convert the Pydantic model to a JSON-compatible dict\njson_compatible_item = jsonable_encoder(item)\n\nprint(json_compatible_item)\n```\n\nIn this example, `jsonable_encoder()` converts the `Item` Pydantic model to a `dict` with the `created_at` field converted to a string in ISO format, making it compatible with JSON.", + "0525d6f89b1b9df3": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "7fe9e8369218cc05": "In FastAPI, the main difference between using `async def` and `def` for endpoints (or path operations) lies in how the framework handles the execution of these functions.\n\nWhen you declare an endpoint with `def`, FastAPI runs it in an external thread pool. This is done to prevent blocking the server, as `def` functions are synchronous and can block the event loop if they perform blocking operations (like I/O operations).\n\nOn the other hand, when you declare an endpoint with `async def`, FastAPI awaits it directly. This allows the endpoint to perform asynchronous operations using `await`, which can improve performance by not blocking the event loop.\n\nHere are some key points to consider:\n\n* Use `async def` when:\n * You're using third-party libraries that support asynchronous operations with `await`.\n * Your endpoint needs to perform asynchronous operations.\n* Use `def` when:\n * You're using third-party libraries that don't support asynchronous operations.\n * Your endpoint performs blocking operations (like I/O operations).\n\nYou can mix `def` and `async def` endpoints in your FastAPI application. FastAPI will handle them appropriately to ensure asynchronous behavior and high performance.\n\nIt's also worth noting that the same rules apply to dependencies. You can use `async def` or `def` for dependencies, and FastAPI will handle them accordingly.\n\nIn summary, the choice between `async def` and `def` for endpoints depends on the specific requirements of your application and the libraries you're using. By choosing the right approach, you can ensure high performance and efficient asynchronous behavior in your FastAPI application [1][4][5].", + "4f9d5f284d7714f4": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "d4f387b7b4d495ba": "To run cleanup code after the response is sent, a dependency can use the default scope `\"request\"`. \n\nHere's an example [5]:\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\ndef get_db():\n db = DBSession()\n try:\n yield db\n finally:\n db.close()\n\n\nDBDep = Annotated[DBSession, Depends(get_db)]\n\n\n@app.get(\"/items/\")\nasync def read_items(db: DBDep):\n return db.query(Item).all()\n```\nIn this case, the exit code (i.e., `db.close()`) will be executed after the response is sent back to the client.\n\nAlternatively, you can explicitly specify the scope as `\"request\"` [1]:\n```python\ndef get_db():\n db = DBSession()\n try:\n yield db\n finally:\n db.close()\n\nDBDep = Annotated[DBSession, Depends(get_db, scope=\"request\")]\n```\nThis achieves the same result as the previous example.\n\nIt's worth noting that if you want the cleanup code to run before the response is sent, you can use the scope `\"function\"` [1][5]:\n```python\ndef get_username():\n try:\n yield \"Rick\"\n finally:\n print(\"Clean up before response is sent\")\n\nUserNameDep = Annotated[str, Depends(get_username, scope=\"function\")]\n```", + "6e8fab1e7839fef0": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "ae3ccb96a503b630": "You can customize or extend the generated OpenAPI schema by overriding the defaults. This can be achieved by using a utility function to generate the OpenAPI schema and then modifying it as needed.\n\nFirst, create your FastAPI application as normal. Then, use the same utility function to generate the OpenAPI schema inside a custom function, such as `custom_openapi()`. \n\nYou can then modify the OpenAPI schema by adding custom extensions, such as a custom logo for ReDoc.\n\nTo avoid generating the schema every time a user opens your API docs, you can cache the OpenAPI schema using the `.openapi_schema` property.\n\nFinally, replace the `.openapi()` method with your custom function.\n\nHere's an example of how you can do this [1]:\n- Write your FastAPI application as normal.\n- Generate the OpenAPI schema using a utility function.\n- Modify the OpenAPI schema as needed.\n- Cache the OpenAPI schema.\n- Override the `.openapi()` method with your custom function.\n\nAdditionally, you can declare extra information in `Field`, `Query`, `Body`, etc., which will be included in the generated JSON Schema [4].\n\nIt's also worth noting that FastAPI internally generates the OpenAPI schema and stores it in the `app.openapi_schema` attribute. If you need to modify the generated OpenAPI schema, you can do so by modifying this attribute [3]. \n\nOpenAPI and JSON Schema have their own ways of handling examples, and understanding these can help you customize your schema further [5].", + "95a2da15d350f536": "```\n{\n \"faithful\": false,\n \"correct\": true\n}\n```", + "5252dacaf76f2448": "When request validation fails in FastAPI, it returns a `422 Unprocessable Entity` error response by default. This response includes a JSON payload with details about the validation errors.\n\nTo customize this error response, you can override the default exception handler for `RequestValidationError`. Here's an example:\n\n```python\nfrom fastapi import FastAPI, Request, status\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.responses import JSONResponse\nfrom fastapi.encoders import jsonable_encoder\n\napp = FastAPI()\n\n@app.exception_handler(RequestValidationError)\nasync def validation_exception_handler(request: Request, exc: RequestValidationError):\n return JSONResponse(\n status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,\n content={\"detail\": jsonable_encoder(exc.errors())},\n )\n```\n\nHowever, note that `RequestValidationError` is not a sub-class of Pydantic's `ValidationError` as stated in the documentation. Instead, it's a custom exception in FastAPI.\n\nIf you want to handle both `RequestValidationError` and `ValidationError`, you can create separate exception handlers for each:\n\n```python\nfrom fastapi import FastAPI, Request, status\nfrom fastapi.exceptions import RequestValidationError, ValidationError\nfrom fastapi.responses import JSONResponse, PlainTextResponse\n\napp = FastAPI()\n\n@app.exception_handler(RequestValidationError)\nasync def request_validation_exception_handler(request: Request, exc: RequestValidationError):\n return JSONResponse(\n status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,\n content={\"detail\": exc.errors()},\n )\n\n@app.exception_handler(ValidationError)\nasync def validation_exception_handler(request: Request, exc: ValidationError):\n return PlainTextResponse(\n str(exc), status_code=status.HTTP_500_INTERNAL_SERVER_ERROR\n )\n```", + "614f0d36cc33f55a": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "ffe9db8cca95e461": "The OAuth2 password flow in FastAPI works as follows:\n\n* The user types their `username` and `password` in the frontend and hits `Enter`.\n* The frontend sends the `username` and `password` to a specific URL in the API, declared with `tokenUrl=\"token\"`.\n* The API checks the `username` and `password` and responds with a \"token\", which is a string that can be used to verify the user.\n* The frontend stores the token temporarily.\n* When the frontend needs to fetch more data from the API, it sends a header `Authorization` with a value of `Bearer` plus the token.\n\nFastAPI provides tools to implement this security feature, including the `OAuth2PasswordBearer` class, which is used to create an instance that handles the OAuth2 password flow. The `tokenUrl` parameter is passed to this instance, which specifies the URL that the client will use to send the `username` and `password` to get a token.\n\nThe `OAuth2PasswordRequestForm` class is used to collect the `username` and `password` as form data for the OAuth2 password flow. This class is a dependency that can be used in a path operation to handle the login.\n\nHere's an example of how to use `OAuth2PasswordRequestForm`:\n```python\nfrom typing import Annotated\nfrom fastapi import Depends, FastAPI\nfrom fastapi.security import OAuth2PasswordRequestForm\n\napp = FastAPI()\n\n@app.post(\"/login\")\ndef login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):\n # Handle the login\n pass\n```\nFastAPI also provides another class, `OAuth2PasswordRequestFormStrict`, which is similar to `OAuth2PasswordRequestForm` but requires the client to send the form field `grant_type` with the value `\"password\"`, which is required in the OAuth2 specification.\n\nThe `OAuth2PasswordBearer` class can be used to protect routes and ensure that only authenticated users can access them. For example:\n```python\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n\n@app.get(\"/protected\")\ndef protected_route(token: str = Depends(oauth2_scheme)):\n # Only authenticated users can access this route\n pass\n```", + "fbcfcab03449064b": "```json\n{\n \"faithful\": false,\n \"correct\": false\n}\n```", + "3ae3c6b0ce4b62ac": "You can run code on application startup and shutdown using event handlers.\n\n## Running on Startup and Shutdown\n\nThere are two ways to handle startup and shutdown events in FastAPI: using the `lifespan` parameter or the deprecated `startup` and `shutdown` events.\n\n### Using Lifespan\n\nThe recommended way is to use the `lifespan` parameter of the `FastAPI` app. This approach is more modern and flexible.\n\n### Using Startup and Shutdown Events\n\nAlternatively, you can use the deprecated `startup` and `shutdown` events. However, this approach is less recommended and might be removed in the future.\n\n## Code Examples\n\n### Using Lifespan\n\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI(\n lifespan=async def(app: FastAPI) -> None:\n # Code to run on startup\n print(\"Startup\")\n try:\n # Code to run while the application is running\n yield\n finally:\n # Code to run on shutdown\n print(\"Shutdown\")\n```\n\n### Using Startup and Shutdown Events\n\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.on_event(\"startup\")\nasync def startup_event():\n # Code to run on startup\n print(\"Startup\")\n\n@app.on_event(\"shutdown\")\nasync def shutdown_event():\n # Code to run on shutdown\n print(\"Shutdown\")\n```\n\n## Testing Events\n\nWhen testing your application, you can use the `TestClient` with a `with` statement to run lifespan events.\n\n```python\nfrom fastapi.testclient import TestClient\n\nclient = TestClient(app)\n\nwith client:\n # Code to test\n pass\n```\n\nFor deprecated `startup` and `shutdown` events, you can use the `TestClient` as follows:\n\n```python\nfrom fastapi.testclient import TestClient\n\nclient = TestClient(app)\n\n# Code to test\n```", + "76f5f1be30b4ec2b": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "27efb94fd0315db1": "You can mount a sub-application under a path prefix in FastAPI. \n\n## Mounting a Sub-Application\n\nTo mount a sub-application, you create a main FastAPI application and a sub-application, then use the `mount` method to add the sub-application to the main application at a specific path.\n\nHere's an example:\n\n```python\nfrom fastapi import FastAPI\n\n# Create the main application\napp = FastAPI()\n\n# Create a sub-application\nsubapi = FastAPI()\n\n# Mount the sub-application at /subapi\napp.mount(\"/subapi\", subapi)\n```\n\n## Using APIRouter\n\nHowever, mounting a sub-application under an `APIRouter` is not currently supported. The `APIRouter` class in FastAPI does have a `mount` method, but it does not work as expected.\n\nAccording to the comments in [issue #10180][5], the best practice is to mount your sub-application directly to the main FastAPI instance using the full path prefix:\n\n```python\napp.mount(\"/api/v1/sub\", sub_app)\n```\n\nThis ensures that the routing table and the `root_path` (for Swagger UI) are handled correctly.\n\n## Proxy and Sub-Applications\n\nWhen using a proxy with a stripped path prefix and mounting sub-applications, FastAPI will internally use the `root_path` smartly, so it will just work [1].\n\nFor example, if you have a proxy that adds a path prefix `/api/v1` to your application, you can use `root_path` to configure your application:\n\n```python\napp = FastAPI(root_path=\"/api/v1\")\n```\n\nAnd then mount a sub-application:\n\n```python\napp.mount(\"/subapi\", subapi)\n```\n\nThe sub-application will be served at `/api/v1/subapi`. \n\n## Conclusion\n\nIn summary, you can mount a sub-application under a path prefix in FastAPI using the `mount` method. However, mounting a sub-application under an `APIRouter` is not currently supported. When using a proxy with a stripped path prefix, you can use `root_path` to configure your application and mount sub-applications as needed. \n\n[1]: docs/en/docs/advanced/behind-a-proxy.md\n[2]: docs/en/docs/advanced/sub-applications.md\n[3]: docs/en/docs/advanced/sub-applications.md\n[4]: docs/en/docs/advanced/behind-a-proxy.md\n[5]: issues/10180.json", + "80566ebd60856274": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "0925f73742106e8a": "FastAPI runs regular `def` endpoints without blocking the event loop by executing them in an external threadpool. This is done to prevent blocking the server when a synchronous function is called.\n\nWhen a path operation function is declared with a normal `def` instead of `async def`, FastAPI runs it in an external threadpool that is then awaited, instead of being called directly. This allows the server to continue handling other requests while the synchronous function is being executed.\n\nThe same applies to dependencies. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool.\n\nThis is implemented in the `run_endpoint_function` function in `fastapi/routing.py` [4], which checks if the dependant function is a coroutine or not. If it's not a coroutine, it runs it in a threadpool using `run_in_threadpool`.\n\nIt's worth noting that using `async def` is recommended unless your path operation functions use code that performs blocking I/O. In cases where blocking code needs to be run, it's better to use a threadpool or asyncer to avoid blocking the event loop [2]. \n\nFastAPI's approach allows it to handle both synchronous and asynchronous code efficiently, making it a flexible and high-performance framework for building APIs. \n\nFor more information on how FastAPI handles concurrency and async/await, see the documentation [1]. \n\nAdditionally, when testing FastAPI applications, it's essential to consider the asynchronous nature of the framework, even when using synchronous test functions. The `TestClient` provided by FastAPI can be used for testing, but it may not work as expected when used inside asynchronous test functions. Instead, HTTPX can be used directly to test the API [5].", + "18577ea41f74136c": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "1387dc17a2283033": "To manage configuration and settings with environment variables, you can utilize Pydantic's `Settings` management feature. This involves [installing `pydantic-settings`][1] and creating a `Settings` object by subclassing `BaseSettings` from Pydantic.\n\nYou declare class attributes with type annotations and optional default values, similar to Pydantic models. Pydantic will then read environment variables in a case-insensitive manner, convert and validate the data according to the declared types.\n\nHere are the general steps:\n\n1. **Install `pydantic-settings`**: You can install it directly or as part of the `all` extras with FastAPI.\n2. **Create the `Settings` object**: Subclass `BaseSettings` and define your settings with type annotations.\n3. **Use the `settings` object**: Access your application's configurations through this object.\n\nYou can also [place your settings in another module][2], such as a `config.py` file, and import it into your main application file.\n\nAdditionally, Pydantic Settings allows for [using settings in a dependency][4], which is particularly useful for testing, as you can easily override settings.\n\nKey benefits include:\n- Leveraging Pydantic models' validation features for your settings.\n- Simplifying testing by using dependencies.\n- Compatibility with `.env` files.\n- Optimization with `@lru_cache` to avoid repetitive reads of dotenv files.\n\nFor more detailed information and examples, refer to the [Pydantic Settings documentation](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) and [Settings and Environment Variables](docs/en/docs/advanced/settings.md) in the FastAPI documentation.", + "5009c695d97aed39": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "d05a89f6a59b933d": "The `APIRouter` class is defined in the `fastapi.routing` module, specifically in the `fastapi/routing.py` file [5]. However, you can import it directly from `fastapi` using `from fastapi import APIRouter` [1].", + "71d1f396164e7663": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "77445a7c8d783ae8": "The `OAuth2PasswordBearer` class is implemented in the `fastapi/security/oauth2.py` file [1].", + "203739885690f31b": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "dcaf2b0d81cecb06": "The `jsonable_encoder` function is implemented in [2] (code: fastapi/encoders.py). \n\nYou can also find more information about it in the documentation [1] (doc: docs/en/docs/tutorial/encoder.md) and [3] (doc: docs/en/docs/tutorial/encoder.md). \n\nAdditionally, a reference to this function can be found at [4] (doc: docs/en/docs/reference/encoders.md).", + "c87cbf4c7f276bee": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "050bc1e8ebaa6d56": "The `BackgroundTasks` class is defined in [4]:\n\n```python\nclass BackgroundTasks(StarletteBackgroundTasks):\n```\n\nIt is also imported from `fastapi` and can be used directly [3]. \n\nThe actual implementation comes from [`starlette.background`](https://www.starlette.dev/background/), but it's included in FastAPI for convenience [1].", + "29bd0311e207e49e": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "8cbfb278164becdf": "The definition of FastAPI's `HTTPException` can be found in [1]. Specifically, it is defined in the `fastapi/exceptions.py` file. \n\nHere's a brief description of the `HTTPException` class:\n- It is used to show errors to the client.\n- It is typically used for client errors, invalid authentication, invalid data, etc., not for server errors in your code. \n\nThe `HTTPException` class has an initializer that takes in parameters such as `status_code`, `detail`, and `headers`. \n\nYou can raise an `HTTPException` in your own code to handle errors. For example:\n\n```python\nfrom fastapi import FastAPI, HTTPException\n\napp = FastAPI()\n\nitems = {\"foo\": \"The Foo Wrestlers\"}\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: str):\n if item_id not in items:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return {\"item\": items[item_id]}\n```", + "2304a6e854d71d0e": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "e26dfab244b4632b": "The main FastAPI application class is defined in the `FastAPI` class, which can be imported directly from `fastapi` [2].", + "e0e28a9dc61ae8fe": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "b46d86b236ab5d45": "The functions `Path`, `Query`, and `Body` are not explicitly mentioned in the provided context chunks. However, based on the context, it can be inferred that they are likely part of the **FastAPI** framework.\n\nIn FastAPI, these functions are actually imported from `fastapi` module.\n\nYou can find their definition and usage in the official FastAPI documentation and source code.\n\nFor example, you can use them as follows:\n\n* `Path`: `Path(..., description=\"Path parameter\")`\n* `Query`: `Query(..., description=\"Query parameter\")`\n* `Body`: `Body(..., description=\"Body parameter\")`\n\nThese functions are used to declare and document path, query, and body parameters in your FastAPI application. \n\nHere's an example:\n```python\nfrom fastapi import FastAPI, Path, Query, Body\n\napp = FastAPI()\n\n@app.get(\"/items/\")\nasync def read_items(\n item_id: int = Path(..., title=\"The ID of the item to get\"),\n q: str = Query(None, description=\"Query string\"),\n item: dict = Body(None, description=\"Item to post\")\n):\n return {\"item_id\": item_id, \"q\": q, \"item\": item}\n```", + "e2c633f1843cf87b": "```json\n{\n \"faithful\": false,\n \"correct\": false\n}\n```", + "fd7e739d99f57b10": "The `TestClient` that FastAPI provides for testing is located in `fastapi.testclient` [1]. It can be imported directly as shown below:\n\n```python\nfrom fastapi.testclient import TestClient\n```\n\nThis `TestClient` is actually the same as the one provided by Starlette, which is imported as [4]:\n```python\nfrom starlette.testclient import TestClient as TestClient # noqa\n```", + "b080d4c5f7bed2b8": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "5b85a046469e2afc": "To connect FastAPI to MongoDB, you can use the `motor` library, which is an asynchronous MongoDB driver. Here's a step-by-step guide:\n\n### Install Required Libraries\n\nFirst, install the required libraries using pip:\n```bash\npip install fastapi motor\n```\n### Create a MongoDB Connection\n\nCreate a new file called `database.py` with the following code:\n```python\nfrom motor.motor_asyncio import AsyncIOMotorClient\n\nMONGO_URL = \"mongodb://localhost:27017/\"\nclient = AsyncIOMotorClient(MONGO_URL)\n\ndb = client[\"mydatabase\"]\ncollection = db[\"mycollection\"]\n```\nReplace `MONGO_URL` with your MongoDB connection URL.\n\n### Create a FastAPI App\n\nCreate a new file called `main.py` with the following code:\n```python\nfrom fastapi import FastAPI\nfrom database import collection\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def read_root():\n return {\"message\": \"Hello, World!\"}\n\n@app.get(\"/items/\")\nasync def read_items():\n items = await collection.find().to_list(length=100)\n return items\n```\nIn this example, we're using the `collection` object to query the MongoDB database.\n\n### Run the App\n\nRun the app using:\n```bash\nuvicorn main:app --host 0.0.0.0 --port 8000 --reload\n```\nOpen your browser and navigate to `http://localhost:8000/items/` to see the data from your MongoDB database.\n\n### Using Dependency Injection\n\nTo make your code more organized and reusable, you can use FastAPI's dependency injection system. Create a new file called `dependencies.py` with the following code:\n```python\nfrom fastapi import Depends\nfrom motor.motor_asyncio import AsyncIOMotorClient\n\nMONGO_URL = \"mongodb://localhost:27017/\"\n\nasync def get_mongo_client():\n client = AsyncIOMotorClient(MONGO_URL)\n return client\n\nasync def get_collection(client: AsyncIOMotorClient = Depends(get_mongo_client)):\n db = client[\"mydatabase\"]\n collection = db[\"mycollection\"]\n return collection\n```\nThen, update your `main.py` file to use the dependency injection:\n```python\nfrom fastapi import FastAPI\nfrom dependencies import get_collection\n\napp = FastAPI()\n\n@app.get(\"/items/\")\nasync def read_items(collection = Depends(get_collection)):\n items = await collection.find().to_list(length=100)\n return items\n```\nThis way, you can easily switch to a different MongoDB database or collection by updating the dependency injection.\n\n### Example Use Case\n\nHere's an example use case where you can create, read, update, and delete (CRUD) items in your MongoDB database:\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom dependencies import get_collection\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass Item(BaseModel):\n name: str\n price: float\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, collection = Depends(get_collection)):\n result = await collection.insert_one(item.dict())\n return {\"_id\": result.inserted_id}\n\n@app.get(\"/items/\")\nasync def read_items(collection = Depends(get_collection)):\n items = await collection.find().to_list(length=100)\n return items\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: str, collection = Depends(get_collection)):\n item = await collection.find_one({\"_id\": item_id})\n if item is None:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return item\n\n@app.put(\"/items/{item_id}\")\nasync def update_item(item_id: str, item: Item, collection = Depends(get_collection)):\n result = await collection.update_one({\"_id\": item_id}, {\"$set\": item.dict()})\n if result.modified_count == 0:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return {\"message\": \"Item updated\"}\n\n@app.delete(\"/items/{item_id}\")\nasync def delete_item(item_id: str, collection = Depends(get_collection)):\n result = await collection.delete_one({\"_id\": item_id})\n if result.deleted_count == 0:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return {\"message\": \"Item deleted\"}\n```\nThis example demonstrates how to create, read, update, and delete items in your MongoDB database using FastAPI and the `motor` library.", + "51d80b0f24573f8f": "FastAPI does not have built-in rate limiting. However, you can implement rate limiting using third-party libraries or by creating a custom solution.\n\nRegarding the performance issues you're experiencing, there could be several factors contributing to this, such as database queries, concurrent requests, or server resources. To better understand and address the issue, more information about your implementation and setup would be helpful.\n\nIt's also worth noting that FastAPI is designed to handle a large number of concurrent requests efficiently. However, the actual performance may vary depending on your specific use case and environment.\n\nYou can refer to the [FastAPI documentation]([2]) for more information on deployment and versioning. Additionally, you can explore [issue #12963]([5]) and other related issues, such as [issue #15578]([1]) and [issue #15612]([3]), which discuss performance and versioning concerns. \n\nFastAPI supports the latest Python versions, including [Python 3.12]([4]).", + "34c799679e2e3a0a": "To integrate Celery task queues with FastAPI, you can follow these steps:\n\n## Step 1: Install Required Packages\n\nFirst, you need to install the required packages. You will need `celery`, `fastapi`, and a message broker like `redis` or `rabbitmq`. For this example, we will use `redis`.\n\n```bash\npip install fastapi celery redis\n```\n\n## Step 2: Set Up Celery\n\nNext, you need to set up Celery with your message broker. Here is an example of how to set up Celery with Redis:\n\n```python\n# celery_config.py\nfrom celery import Celery\n\ncelery = Celery(\"tasks\", broker=\"redis://localhost:6379/0\")\ncelery.conf.update({\n \"CELERY_RESULT_BACKEND\": \"redis://localhost:6379/0\",\n \"CELERY_RESULT_SERIALIZER\": \"json\",\n \"CELERY_ACCEPT_CONTENT\": [\"json\"]\n})\n```\n\n## Step 3: Create Tasks\n\nNow, you can create tasks using the Celery instance:\n\n```python\n# tasks.py\nfrom celery_config import celery\n\n@celery.task\ndef add(x, y):\n return x + y\n```\n\n## Step 4: Integrate with FastAPI\n\nFinally, you can integrate Celery with FastAPI:\n\n```python\n# main.py\nfrom fastapi import FastAPI\nfrom tasks import add\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef read_root():\n task = add.delay(4, 4)\n return {\"task_id\": task.id}\n```\n\nIn this example, when you visit the root URL, it will start a new task to add 4 and 4. The task ID will be returned in the response.\n\n## Additional Considerations\n\n- Make sure to run the Celery worker using `celery -A tasks.celery worker --loglevel=info` to process the tasks.\n- You can use `result.get()` to get the result of the task. However, be aware that this can block the execution of your FastAPI application.\n- You can also use `BackgroundTasks` in FastAPI for simple background tasks. However, for more complex task queues, Celery is a better choice.\n\n## Example Use Case\n\nHere is an example use case where you can use Celery with FastAPI to send emails:\n\n```python\n# tasks.py\nfrom celery_config import celery\nfrom fastapi_mail import FastAPIMail\n\n@celery.task\ndef send_email(to, subject, body):\n mail = FastAPIMail()\n mail.send_email(to, subject, body)\n```\n\n```python\n# main.py\nfrom fastapi import FastAPI\nfrom tasks import send_email\n\napp = FastAPI()\n\n@app.post(\"/send-email/\")\ndef send_email_endpoint(to: str, subject: str, body: str):\n task = send_email.delay(to, subject, body)\n return {\"task_id\": task.id}\n```\n\nIn this example, when you send a POST request to `/send-email/`, it will start a new task to send an email. The task ID will be returned in the response.", + "f95be30c82eefc3c": "I am unable to fulfill this request as the necessary information is not present in the provided context. However, I can guide you on how to generally approach using FastAPI with the Django ORM.\n\nFastAPI and Django are two different frameworks used for building web applications. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. Django, on the other hand, is a high-level Python web framework that encourages rapid development and clean, pragmatic design.\n\nTo use FastAPI with the Django ORM, you would typically use the Django ORM to interact with your database and FastAPI to create the API endpoints. Here are general steps you might follow:\n\n1. **Set up your Django project**: First, ensure you have Django installed. Then, create a new Django project and an app within that project.\n\n2. **Define your models**: In your Django app, define your models. These models will represent your database tables.\n\n3. **Create API endpoints with FastAPI**: Create a new FastAPI application. To use Django models with FastAPI, you might need to create Pydantic models that mirror your Django models or use an library that allows you to directly use Django models.\n\n4. **Integrate Django ORM with FastAPI**: You can use the Django ORM directly in your FastAPI route handlers. However, this might require some additional setup, like ensuring that the Django project's settings are accessible and that the database connection is properly configured.\n\n5. **Run your FastAPI application**: Ensure that your FastAPI app is running and can interact with your Django ORM.\n\nBelow is a simplified example:\n\n```python\n# mydjangoapp/models.py\nfrom django.db import models\n\nclass Item(models.Model):\n name = models.CharField(max_length=100)\n description = models.TextField()\n```\n\n```python\n# main.py (FastAPI app)\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom mydjangoapp.models import Item\nfrom django.core.management import call_command\nimport os\nimport sys\n\n# Setup Django environment\nsys.path.append('/path/to/your/django/project')\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_django_project.settings')\n\nimport django\ndjango.setup()\n\napp = FastAPI()\n\nclass ItemSchema(BaseModel):\n name: str\n description: str\n\n@app.get(\"/items/\")\nasync def read_items():\n items = Item.objects.all()\n return [{\"name\": item.name, \"description\": item.description} for item in items]\n```\n\n**Note**: This example assumes you have both Django and FastAPI installed and have replaced `'/path/to/your/django/project'`, `'your_django_project.settings'` with your actual project path and settings module name.\n\nFor more detailed instructions and to handle things like database connections properly, consider looking into libraries or frameworks that help integrate Django and FastAPI, such as `django-channels` for real-time capabilities or third-party libraries for direct integration. \n\nHowever, the provided context does not contain information related to this question. If you have a more specific question related to FastAPI or Django, feel free to ask.", + "60706099cf319c3b": "No, FastAPI does not include a built-in admin dashboard. However, there is an issue [2] discussing the addition of a built-in job queue and background task management with a monitoring dashboard, which could potentially lead to the development of an admin dashboard in the future.\n\nThat being said, you can serve a static frontend app, such as an admin dashboard, using `app.frontend()` [1]. \n\nAdditionally, there are third-party libraries and tools available that provide admin dashboards for FastAPI applications. \n\nIf you're looking for a specific feature like an automatic OPTIONS request with route schema, there is an issue [3] discussing this topic. \n\nHowever, for now, no built-in admin dashboard is available.", + "756a8bb84822f315": "To schedule recurring cron jobs inside FastAPI, you can utilize libraries like `apscheduler`. Here's a basic example of how to integrate it with FastAPI:\n\n### Step 1: Install `apscheduler`\n\nFirst, you need to install `apscheduler`. You can do this by running:\n\n```bash\npip install apscheduler\n```\n\n### Step 2: Implement Cron Job\n\nNext, you can implement a cron job in your FastAPI application. Below is an example:\n\n```python\nfrom fastapi import FastAPI\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.triggers.cron import CronTrigger\n\napp = FastAPI()\n\ndef my_task():\n # Your task code here\n print(\"Cron job executed\")\n\n# Create a scheduler\nscheduler = BackgroundScheduler()\n\n# Define the cron trigger\ntrigger = CronTrigger(hour=18, minute=35)\n\n# Add the job to the scheduler\nscheduler.add_job(my_task, trigger)\n\n# Start the scheduler\nscheduler.start()\n\n@app.get(\"/\")\ndef read_root():\n return {\"message\": \"FastAPI application with cron job\"}\n```\n\nHowever, remember that the scheduler runs in the background, and your FastAPI application needs to be running for the scheduler to execute the jobs.\n\n### Considerations for Production\n\nWhen running your FastAPI application in production, ensure that it remains running without interruption. You can achieve this by using tools like `systemd`, `supervisor`, or containerization with `Docker`. \n\nFor example, you can use `systemd` to create a service that runs your FastAPI application:\n\n```bash\n[Unit]\nDescription=My FastAPI Application\nAfter=network.target\n\n[Service]\nUser=myuser\nExecStart=/usr/bin/uvicorn main:app --host 0.0.0.0 --port 8000\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\n```\n\nThis ensures your application restarts if it crashes or if the server reboots.\n\n### Using `fastapi run`\n\nWhen using `fastapi run`, it starts FastAPI in production mode. By default, **auto-reload** is disabled, and it listens on all available IP addresses, making it publicly accessible. \n\nHowever, for running background tasks or cron jobs, consider using a dedicated scheduler like `apscheduler` or external services like `Celery` with a message broker.\n\n### External Documentation\n\nFor more detailed information on deployment and background tasks, refer to the [deployment documentation](deployment/index.md) and consider exploring job queue patterns and task orchestration standards for complex workflows.\n\n### Example Use Case\n\nHere's an advanced example integrating `apscheduler` with FastAPI for scheduling tasks:\n\n```python\nfrom fastapi import FastAPI\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.triggers.cron import CronTrigger\nimport asyncio\n\napp = FastAPI()\n\nasync def my_async_task():\n # Asynchronous task example\n await asyncio.sleep(1)\n print(\"Asynchronous task completed\")\n\ndef schedule_task():\n scheduler = BackgroundScheduler()\n trigger = CronTrigger(hour=18, minute=35)\n scheduler.add_job(my_async_task, trigger)\n scheduler.start()\n\n@app.on_event(\"startup\")\ndef startup_event():\n schedule_task()\n\n@app.get(\"/\")\ndef read_root():\n return {\"message\": \"FastAPI with scheduled task\"}\n```\n\nThis approach allows you to schedule tasks while keeping your FastAPI application responsive.", + "d2765aa381a02946": "FastAPI does not have built-in database migration support. However, you can use libraries like Alembic, which is a popular migration tool for SQL databases, or SQLModel's built-in migration support.\n\nHere are some options you can consider:\n\n* **Alembic**: Alembic is a lightweight, straightforward, and programmatically medium-level SQL migration tool for Python. It can be used with FastAPI and SQL databases like PostgreSQL, MySQL, and SQLite.\n* **SQLModel**: SQLModel is an ORM (Object-Relational Mapping) tool that provides a simple and intuitive way to interact with databases using Python. It has built-in support for database migrations.\n\nYou can also consider using other migration tools like **Pydantic** with **sqlalchemy** or **Django**'s built-in migration system if you're building a Django application.\n\nHere's an example of how you might use Alembic with FastAPI:\n\n```python\n# alembic.ini\nsqlalchemy.url = postgresql://user:password@host:port/dbname\n\n# alembic/env.py\nfrom logging.config import fileConfig\n\nfrom sqlalchemy import engine_from_config\nfrom sqlalchemy import pool\n\nfrom alembic import context\n\nfrom myapp.core.database_engine.db_core import Base # noqa: F401\n\nconfig = context.config\n\nfileConfig(config.config_file_name)\n\ntarget_metadata = Base.metadata\n\ndef run_migrations_offline():\n url = config.get_main_option(\"sqlalchemy.url\")\n context.configure(\n url=url,\n target_metadata=target_metadata,\n literal_binds=True,\n dialect_opts={\"paramstyle\": \"named\"},\n )\n\n with context.begin_transaction():\n context.run_migrations()\n\n\ndef run_migrations_online():\n connectable = engine_from_config(\n config.get_section(config.config_ini_section),\n prefix='sqlalchemy.',\n poolclass=pool.NullPool)\n\n with connectable.connect() as connection:\n context.configure(\n connection=connection, target_metadata=target_metadata\n )\n\n with context.begin_transaction():\n context.run_migrations()\n\nif context.is_offline_mode():\n run_migrations_offline()\nelse:\n run_migrations_online()\n```\n\nTo create a new migration, you can use the following command:\n\n```bash\nalembic revision --autogenerate -m \"add new table\"\n```\n\nAnd to apply the migrations, you can use:\n\n```bash\nalembic upgrade head\n```", + "4ebc7d3c6c4346ee": "You can set a custom status code for an endpoint by passing the `status_code` parameter to the path operation decorator, such as `@app.get()` or `@app.post()`. This parameter receives a number with the HTTP status code or an `IntEnum`, such as Python's `http.HTTPStatus` [5].\n\nFor example:\n```python\nfrom fastapi import FastAPI, status\n\napp = FastAPI()\n\n@app.get(status_code=200)\nasync def read_items():\n return [{\"item\": \"Item1\"}]\n```\nAlternatively, you can use the shortcut constants in `status` to avoid remembering the HTTP status code numbers [2].\n\nIf you need to return a different status code than the default one based on certain conditions, you can return a `Response` object directly, such as a `JSONResponse`, and set the custom status code [1].\n\nFor instance:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.post()\nasync def create_item(item):\n # Create item logic here\n if item_exists:\n return JSONResponse(content={\"message\": \"Item created\"}, status_code=201)\n else:\n return JSONResponse(content={\"message\": \"Item updated\"}, status_code=200)\n```", + "0ff0e9755492751e": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "216c2e9d156287d1": "To receive an uploaded file in an endpoint, you can define a path operation function parameter to be of type `UploadFile` [2]. \n\nYou can import `UploadFile` directly from `fastapi`:\n```python\nfrom fastapi import UploadFile\n```\nAdditionally, make sure to install `python-multipart` as uploaded files are sent as \"form data\" [1].\n\nYou can also use `File` to define files to be uploaded by the client [5]. \n\nHere's an example of how to declare file parameters:\n```python\nfrom fastapi import File, UploadFile\n```\nYou can declare multiple `File` and `Form` parameters in a path operation, but you can't also declare `Body` fields that you expect to receive as JSON [4]. \n\nFor more details, you can check the documentation for `UploadFile` [2] and request files [1][3].", + "ecb3f2226a8d14d7": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "882e2e97200e863f": "You can define background tasks to be run after returning a response using the `BackgroundTasks` class from FastAPI. Here's an example [2][4]:\n```python\nfrom fastapi import BackgroundTasks, FastAPI\n\napp = FastAPI()\n\ndef write_notification(email: str, message=\"\"):\n # Your task code here\n pass\n\n@app.post(\"/send-notification/{email}\")\nasync def send_notification(email: str, background_tasks: BackgroundTasks):\n background_tasks.add_task(write_notification, email, message=\"some notification\")\n return {\"message\": \"Notification sent in the background\"}\n```\nIn this example, the `write_notification` function will be executed in the background after the response is sent.\n\nNote that background tasks only run if a 2xx response is sent back [3]. If you raise an `HTTPException`, the background tasks will not be executed.\n\nIf you want to record something when raising an `HTTPException` in a background task, you can add a try-except block in your task function to handle any exceptions [3]. \n\nAlso, be aware that if you return a `Response` object with its own `background` attribute set, the injected background tasks will be silently discarded [5]. In such cases, you should consider emitting a warning to notify the developer. \n\nFor more information, you can refer to the FastAPI documentation on [Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).", + "bc897fb99c92741d": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "32645b20b4354d12": "To enable CORS in FastAPI, you can use the `CORSMiddleware`. Here's how to do it [2]:\n* Import `CORSMiddleware`.\n* Create a list of allowed origins (as strings).\n* Add it as a \"middleware\" to your FastAPI application.\n\nYou can configure the `CORSMiddleware` with the following parameters:\n* `allow_origins` - A list of origins that should be permitted to make cross-origin requests.\n* `allow_methods` - A list of HTTP methods that should be allowed for cross-origin requests.\n* `allow_headers` - A list of HTTP request headers that should be supported for cross-origin requests.\n\nExample:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\n\norigins = [\"http://localhost:8080\"]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n```\nThis will enable CORS for your FastAPI application, allowing requests from `http://localhost:8080` and other specified origins. For more information, check the [Mozilla CORS documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) [3].", + "f20fa5568907cced": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "ac09398ecc63291c": "You can declare optional query parameters with default values by setting their default to a specific value, such as `None`, or other default values like strings, integers, etc. \n\nFor example, to declare an optional query parameter `q` with a default value of `None`, you can use:\n```python\nq: str | None = None\n```\nAlternatively, you can use other default values, such as:\n```python\nq: str = \"fixedquery\"\n```\nThis makes the `q` query parameter optional and sets its default value to `\"fixedquery\"` [2].\n\nYou can also declare multiple query parameters with different default values, such as:\n```python\nskip: int = 0\nlimit: int | None = None\n```\nIn this case, `skip` has a default value of `0` and `limit` is an optional parameter with a default value of `None` [3][4].", + "15070be3da973bd5": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "ca179046a07dc96c": "You can declare the type of a path parameter in the function using standard Python type annotations. For example, to declare a path parameter `item_id` with type `int`, you can do [1]:\n```python\n# No exact code example in [1], but it points to: \n# ../../docs_src/path_params/tutorial002_py310.py\n```\nHowever an example is given in [4] for string type:\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: str):\n return {\"item_id\": item_id}\n```\nFor an integer type, you would do:\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int):\n return {\"item_id\": item_id}\n```", + "71d4ddda7c0dfb45": "```\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "91fe2fede26628db": "To receive a JSON request body using a Pydantic model, you need to declare a Pydantic model with the fields you want to receive and then use it as a parameter in your route function. \n\nHere's a basic example from [5]:\n```python\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n name: str\n description: str\n price: float\n```\n\nThen, you can use it in your route like this:\n```python\n@app.post(\"/items/\")\nasync def create_item(item: Item):\n return item\n```\nFastAPI will automatically extract the JSON data from the request, validate it against the `Item` model, and return it as a JSON response.\n\nFor more details on how to handle specific types of data, such as bytes as base64, you can refer to [1][2]. \n\nIf you need to handle form data, you can use Pydantic models with the `Form` parameter as shown in [4]. \n\nIf you want to receive bodies of arbitrary dicts, you can declare a body as a `dict` with specific key and value types as shown in [3].", + "278e11db32ceea2b": "```json\n{\n \"faithful\": false,\n \"correct\": true\n}\n```", + "867c92d55fb72612": "To receive form data instead of JSON, you can use `Form` in your FastAPI application. First, ensure you have `python-multipart` installed. You can install it using pip:\n\n```console\n$ pip install python-multipart\n```\n\nThen, define your form parameters using `Form`:\n\n```python\nfrom fastapi import FastAPI, Form\n\napp = FastAPI()\n\n@app.post(\"/login/\")\nasync def login(username: str = Form(...), password: str = Form(...)):\n return {\"username\": username}\n```\n\nIn this example, `username` and `password` are received as form data [5].\n\nAlternatively, if you need to handle files and form data together, you can use both `File` and `Form` parameters:\n\n```python\nfrom fastapi import FastAPI, File, Form\n\napp = FastAPI()\n\n@app.post(\"/upload/\")\nasync def create_upload_file(file: bytes = File(...), filename: str = Form(...)):\n return {\"filename\": filename}\n```\n\nThis way, you can handle both form fields and files in the same request [4]. \n\nNote that when using `Form` and/or `File`, you cannot also declare `Body` fields that expect JSON data, as the request body will be encoded using `multipart/form-data` or `application/x-www-form-urlencoded` instead of `application/json` [2][3].", + "025a4a392c9305f7": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "eb4029f96d955e51": "To return a custom error response with a specific status code and message, you can return a `Response` directly, such as a `JSONResponse`, and set the status code and content accordingly [1].\n\nFor example, you can use `JSONResponse` to return a custom error response:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n # Custom error response\n return JSONResponse(content={\"error\": \"Item not found\"}, status_code=404)\n```\nAlternatively, you can use the `status_code` parameter in a path operation decorator to specify the status code, and return a response with a custom message [2]:\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/items/\", status_code=404)\ndef read_items():\n return {\"error\": \"Item not found\"}\n```\nMake sure to handle the custom response content and status code according to your specific use case. \n\nIf you need to return a custom response directly, you can also use `Response` objects from Starlette, which are also available as `fastapi.responses` [4]. \n\nFor more information on HTTP status codes, you can refer to the documentation [5].", + "c8da15be3d443a11": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "c881da8679f2d974": "You can use the `response_model` parameter in your path operation decorator to control which fields are returned. This is particularly useful when you want to filter data and expose only public fields, while avoiding sensitive information [5].\n\nHere's an example:\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass InternalItem(BaseModel):\n name: str\n description: str | None = None\n secret_key: str\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n\n@app.get(\"/items/me\", response_model=Item)\nasync def get_item() -> Any:\n item = InternalItem(\n name=\"Foo\", description=\"A very nice Item\", secret_key=\"supersecret\"\n )\n return item\n```\nIn this example, even though the `get_item` function returns an `InternalItem` instance, FastAPI will use the `response_model` parameter to filter out the `secret_key` field and return only the fields declared in the `Item` model [5].\n\nYou can also use `response_model_exclude_unset=True` to exclude fields with default values that are not explicitly set [3]. \n\nFor more information, you can check the FastAPI documentation on response models [1][2].", + "c6b9d7a9bd1e0c29": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "c3ad42a7f2a6ce12": "To serve static files like images or CSS, you can use the `StaticFiles` class from `fastapi.staticfiles`. Here's an example [1]:\n```python\nfrom fastapi.staticfiles import StaticFiles\n\n# Mount the StaticFiles instance in a specific path\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n```\nThis will serve static files from the `static` directory at the URL `/static`. For example, if you have a file `styles.css` in the `static` directory, it will be served at `/static/styles.css` [2].\n\nYou can also use `StaticFiles` to serve static files for your API docs. For example, you can self-host the JavaScript and CSS files for Swagger UI and ReDoc [4].\n\nMake sure to replace `\"static\"` with your actual directory name and path. \n\nHere's a code example using `StaticFiles` to serve files:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.staticfiles import StaticFiles\n\napp = FastAPI()\n\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n```", + "09c8ff98f3dc1136": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "a03f9a06dec86afb": "You can write tests for your FastAPI endpoints using the `TestClient` provided by Starlette, which is the foundation of FastAPI. This allows you to use pytest directly with FastAPI [5].\n\nHere's an example of how to test your endpoints:\n\n```python\nfrom fastapi.testclient import TestClient\nfrom .main import app\n\nclient = TestClient(app)\n\ndef test_read_root():\n response = client.get(\"/\")\n assert response.status_code == 200\n assert response.json() == {\"Hello\": \"World\"}\n```\n\nYou can also use asynchronous tests with `async def` functions, which is useful when querying your database asynchronously [1].\n\n```python\nfrom fastapi.testclient import TestClient\nfrom .main import app\n\nclient = TestClient(app)\n\nasync def test_read_root():\n response = client.get(\"/\")\n assert response.status_code == 200\n assert response.json() == {\"Hello\": \"World\"}\n```", + "3c2b6c40445ad22b": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "4d305bd59545bc31": "To use WebSockets in FastAPI, you can create a WebSocket endpoint using the `@app.websocket()` decorator. Here's an example [4]:\n```python\nfrom fastapi import FastAPI, WebSocket\n\napp = FastAPI()\n\n@app.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n while True:\n data = await websocket.receive_text()\n await websocket.send_text(f\"Message text was: {data}\")\n```\nThis code creates a WebSocket endpoint at `/ws` that accepts WebSocket connections, receives text messages, and sends responses back to the client.\n\nYou can also use the `WebSocket` class directly from `fastapi` [5]:\n```python\nfrom fastapi import WebSocket\n```\nFastAPI provides the `WebSocket` class as a convenience, but it comes directly from Starlette [3].\n\nTo try out WebSockets with FastAPI, you can run your application using `fastapi dev` and access it in your browser at `http://127.0.0.1:8000` [2].\n\nFor more information, you can check the FastAPI documentation on WebSockets [1].", + "a1bdbfc2295db01c": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "e3cec4b90a96a8db": "You can set a cookie in a response by declaring a parameter of type `Response` in your path operation function and then setting the cookie in that temporary response object [2].\n\nHere's an example:\n```python\nfrom fastapi import FastAPI, Response\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef read_root(response: Response):\n response.set_cookie(\"cookie_name\", \"cookie_value\")\n return {\"message\": \"Hello World\"}\n```\nAlternatively, you can create a response directly and set cookies in it, and then return it [1]:\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef read_root():\n response = JSONResponse(content={\"message\": \"Hello World\"}, media_type=\"application/json\")\n response.set_cookie(\"cookie_name\", \"cookie_value\")\n return response\n```\nYou can also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse` [1]. \n\nFor more information on available parameters and options, check the [Starlette documentation](https://www.starlette.dev/responses/#set-cookie).", + "3156523ce59b424c": "```\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "643b2f6c9f95fc5b": "You can add custom headers to a response by returning a `Response` directly and passing the headers as an additional parameter [1]. \n\nFor example, you can create a response and add headers:\n```python\nfrom fastapi import FastAPI, Response\n\napp = FastAPI()\n\n@app.get(\"/items/\")\ndef read_items():\n headers = {\"Custom-Header\": \"Custom-Value\"}\n return Response(content=\"Some content\", media_type=\"text/plain\", headers=headers)\n```\nAlternatively, you can add custom headers when handling errors [3].\n\nIt's also worth noting that when returning a custom `Response`, you can add headers directly to the `Response` object [4].\n\nFastAPI also provides the same `starlette.responses` as `fastapi.responses` for convenience [1]. \n\nYou can use `from fastapi import Response` or `from starlette.responses import Response`. \n\nFastAPI provides `fastapi.Response` at the same place as it is used frequently to set headers and cookies. \n\nYou could also add custom proprietary headers using the `X-` prefix [2]. \n\nBut for custom headers to be visible to clients in a browser, you need to add them to your CORS configurations [2].", + "6f41303e745c7775": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "931df72a1774120a": "To implement JWT token authentication, you'll need to follow these steps:\n\n## Step 1: Handle JWT Tokens\nImport the necessary modules, create a random secret key for signing JWT tokens, and define the algorithm and expiration time. Define a Pydantic model for the token endpoint response and create a utility function to generate a new access token [3].\n\n## Step 2: Update the `/token` Path Operation\nCreate a `timedelta` with the expiration time and generate a real JWT access token. Use the `sub` key to store the user's identification [5].\n\n## Step 3: Use OAuth2 with Password and Hashing\nImplement OAuth2 with password and hashing, and use Bearer with JWT tokens. This will involve creating a secure password hashing system and using JWT tokens to authenticate users [2].\n\n## 4: Test the Authentication Flow\nRun the server and test the authentication flow using the provided credentials (username: `johndoe`, password: `secret`). Verify that the token is generated correctly and can be used to access protected endpoints [1].\n\nHere's an example of how to generate a secret key:\n```console\n$ openssl rand -hex 32\n09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\n```\nNote that you should use a secure random secret key and not hardcode it in your application.\n\nFor code implementation details, you can refer to the provided code snippets [3][5]. \n\nI couldn't find a complete executable code example in the provided context chunks. However, the documentation provides a detailed guide on implementing JWT token authentication with FastAPI.", + "bc6361899cc06dda": "```json\n{\n \"faithful\": false,\n \"correct\": false\n}\n```", + "b2c59ef519bc1f5b": "FastAPI's dependency injection system is designed to be simple and intuitive. It allows you to declare dependencies for your path operation functions, and FastAPI will take care of providing those dependencies [1].\n\nHere's how it works:\n\n* You declare a dependency as a function that can take parameters, just like a path operation function.\n* You use the `Depends` annotation to specify that a path operation function depends on another function.\n* FastAPI will then execute the dependency function and inject its result into the path operation function [5].\n\nThe dependency function can return anything, and it can take parameters such as query parameters, path parameters, etc. You can think of it as a path operation function without the decorator [5].\n\nFastAPI's dependency injection system is useful for sharing logic, database connections, security, authentication, and more, while minimizing code repetition [2].\n\nFor example, you can create a dependency function that returns a database paginator, and then use that dependency in a path operation function [4].\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n@dataclass\nclass DatabasePaginator:\n offset: int = 0\n limit: int = 100\n q: str | None = None\n\ndef get_db_paginator(\n offset: int = 0, limit: int = 100, q: str | None = None\n) -> DatabasePaginator:\n return DatabasePaginator(offset=offset, limit=limit, q=q)\n\nPaginatorDep = Annotated[DatabasePaginator, Depends(get_db_paginator)]\n\n@app.get(\"/items/\")\nasync def read_items(paginator: PaginatorDep):\n return paginator.get_page()\n``` [4]\n\nIt's recommended to avoid creating class dependencies when possible, and instead create regular function dependencies that return class instances [4].", + "23be3172bc12523c": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "bd1b73503e8a5ed4": "`jsonable_encoder()` is a function provided by FastAPI to convert data types, such as Pydantic models, to JSON-compatible data structures, like `dict` or `list`. This is necessary when you need to store data in a database or return it in a response, as some data types, like `datetime` objects, are not compatible with JSON [1].\n\nYou need to use `jsonable_encoder()` in scenarios such as [2][4]:\n* Storing data in a database that only accepts JSON-compatible data.\n* Returning a Pydantic model in a response, as responses require JSON-compatible data.\n* When you don't declare a response model, FastAPI will use `jsonable_encoder` to convert the data.\n\nThe function takes an object, like a Pydantic model, and returns a JSON-compatible version. For example, it can convert a Pydantic model to a `dict` and a `datetime` object to a `str` in ISO format [2].\n\nHere's an example of using `jsonable_encoder()`:\n```python\nfrom fastapi.encoders import jsonable_encoder\nfrom datetime import datetime\n\nclass Item:\n def __init__(self, name: str, created_at: datetime):\n self.name = name\n self.created_at = created_at\n\nitem = Item(\"Example Item\", datetime.now())\nencoded_item = jsonable_encoder(item)\n```\nIn this case, `encoded_item` would be a `dict` with the item's data, and `created_at` would be a `str` in ISO format. \n\nThe `jsonable_encoder()` function also accepts several parameters to customize the encoding process, such as `include`, `exclude`, `by_alias`, `exclude_unset`, `exclude_defaults`, and `exclude_none` [3].", + "4b46590df4e9a632": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "43bb72316c32b9c5": "When you declare a *path operation function* with normal `def` instead of `async def`, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server) [1].\n\nUse `async` *path operations* only when fully certain that the logic called inside is compatible with async and await, and that it doesn't block. In case of doubt, or by default, use regular `def` functions. They will be run in a threadpool so they don't block the event loop [3].\n\nYou can mix `def` and `async def` in your *path operation functions* as much as you need and define each one using the best option for you. FastAPI will do the right thing with them [1]. \n\nHere is an example:\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/async-items/\")\nasync def read_async_items():\n data = await some_async_library.fetch_items()\n return data\n\n@app.get(\"/items/\")\ndef read_items():\n data = some_blocking_library.fetch_items()\n return data\n```", + "f0d20e7038ec78d0": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "bfb9e31f6f5ba311": "To run cleanup code after the response is sent, a dependency can use the default scope `\"request\"`. This is the default behavior for dependencies with `yield`, and it ensures that the exit code after `yield` is executed after the response is sent back to the client [1].\n\nHere's an example:\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\ndef get_db():\n db = DBSession()\n try:\n yield db\n finally:\n db.close()\n\n\nDBDep = Annotated[DBSession, Depends(get_db)]\n\n\n@app.get(\"/items/\")\nasync def read_items(db: DBDep):\n return db.query(Item).all()\n```\nIn this case, the `db.close()` statement will be executed after the response is sent [5].\n\nAlternatively, you can explicitly specify the scope as `\"request\"`:\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\ndef get_db():\n db = DBSession()\n try:\n yield db\n finally:\n db.close()\n\n\nDBDep = Annotated[DBSession, Depends(get_db, scope=\"request\")]\n\n\n@app.get(\"/items/\")\nasync def read_items(db: DBDep):\n return db.query(Item).all()\n```\nThis will also ensure that the cleanup code is run after the response is sent [1][4].", + "74e09cdfcb265872": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "f921c54c4c8bcc8e": "To customize or extend the generated OpenAPI schema, you can override the defaults by using a utility function, such as `get_openapi`, to generate the OpenAPI schema and then modify it as needed.\n\nHere's an example of how to add a custom logo to the OpenAPI schema using ReDoc's OpenAPI extension [1]:\n```python\n# Generate the OpenAPI schema\nopenapi_schema = get_openapi(\n title=\"My App\",\n version=\"1.0.0\",\n # ... other parameters ...\n)\n\n# Modify the OpenAPI schema\nopenapi_schema[\"info\"][\"x-logo\"] = {\"url\": \"https://example.com/logo.png\"}\n\n# Cache the OpenAPI schema\napp.openapi_schema = openapi_schema\n```\nAlternatively, you can create a custom `openapi()` function that generates and modifies the OpenAPI schema [1]:\n```python\ndef custom_openapi(self) -> dict[str, Any]:\n # Generate the OpenAPI schema\n openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n # ... other parameters ...\n )\n\n # Modify the OpenAPI schema\n openapi_schema[\"info\"][\"x-logo\"] = {\"url\": \"https://example.com/logo.png\"}\n\n return openapi_schema\n```\nYou can then override the `.openapi()` method with your custom function [1]:\n```python\napp.openapi = custom_openapi\n```\nNote that the `openapi()` method is called internally by FastAPI to generate the OpenAPI schema, and it caches the result in the `app.openapi_schema` attribute [3].", + "4eb8effd5fa2babf": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "a9d6024e984e8194": "When request validation fails in FastAPI, it returns a `RequestValidationError`, which is a sub-class of `ValidationException`, but not directly a sub-class of Pydantic's `ValidationError` as previously documented [1].\n\nThe default error response for `RequestValidationError` includes a JSON payload with a 422 status code, containing details about the validation errors.\n\nTo customize the error response, you can create a custom exception handler for `RequestValidationError`. Here's an example:\n\n```python\nfrom fastapi import FastAPI, Request, Response\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.exception_handler(RequestValidationError)\nasync def validation_exception_handler(request: Request, exc: RequestValidationError):\n return JSONResponse(\n status_code=422,\n content={\"detail\": exc.errors()},\n )\n```\n\nIn this example, we're creating a custom exception handler that returns a JSON response with a 422 status code and the validation error details.\n\nNote that if you want to handle both `RequestValidationError` and `ValidationError`, you need to create separate exception handlers for each, as they are not directly related [1].\n\nAlso, when using Pydantic V2, the OpenAPI entries for `HTTPValidationError` and `ValidationError` might need to be updated [2].", + "dfd299a22e1daed8": "```json\n{\n \"faithful\": false,\n \"correct\": true\n}\n```", + "33ec01743c15b322": "The OAuth2 password flow in FastAPI works as follows [1]:\n* The user types their `username` and `password` in the frontend and hits `Enter`.\n* The frontend sends the `username` and `password` to a specific URL in the API, declared with `tokenUrl=\"token\"`.\n* The API checks the `username` and `password` and responds with a \"token\".\n* The frontend stores the token temporarily.\n* When the frontend needs to fetch more data from the API, it sends a header `Authorization` with a value of `Bearer` plus the token.\n\nTo implement this flow, FastAPI provides tools such as [2]:\n* `OAuth2PasswordBearer`: a class that handles the OAuth2 flow for authentication using a bearer token obtained with a password.\n* `OAuth2PasswordRequestForm`: a dependency class that collects the `username` and `password` as form data for an OAuth2 password flow.\n\nHere's an example of how to use `OAuth2PasswordRequestForm` [3]:\n```python\nfrom typing import Annotated\nfrom fastapi import Depends, FastAPI\nfrom fastapi.security import OAuth2PasswordRequestForm\n\napp = FastAPI()\n\n@app.post(\"/login\")\ndef login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):\n # Process the form data\n return {}\n```\nFastAPI also provides `OAuth2PasswordBearer` to define the token URL [5]:\n```python\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n```", + "0433d5b019806f8c": "```json\n{\n \"faithful\": false,\n \"correct\": true\n}\n```", + "e48f4eb04897534b": "You can run code on application startup and shutdown using event handlers. For startup, use the `\"startup\"` event, and for shutdown, use the `\"shutdown\"` event [3].\n\nTo add a function that should be run before the application starts, declare it with the event `\"startup\"`. Similarly, to add a function that should be run when the application is shutting down, declare it with the event `\"shutdown\"`.\n\nHere's an example of how you can define event handlers:\n\n```python\n@app.on_event(\"startup\")\nasync def startup_event():\n # Code to run on startup\n pass\n\n@app.on_event(\"shutdown\")\nasync def shutdown_event():\n # Code to run on shutdown\n pass\n```\n\nAlternatively, you can use the `lifespan` parameter of the `FastAPI` app, which is the recommended way to handle startup and shutdown events [3].\n\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI(lifespan=async def lifespan(app: FastAPI) -> None:\n # Code to run on startup\n try:\n # Application code\n finally:\n # Code to run on shutdown\n)\n```\n\nNote that if you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called.\n\nYou can also use `APIRouter` to run code on startup and shutdown [1][5].\n\n```python\nfrom fastapi import APIRouter\n\nrouter = APIRouter()\n\n@router.on_event(\"startup\")\nasync def startup_event():\n # Code to run on startup\n pass\n\n@router.on_event(\"shutdown\")\nasync def shutdown_event():\n # Code to run on shutdown\n pass\n```", + "265a9eacb62ac592": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "8e08d994b66cefc2": "You can mount a sub-application under a path prefix using FastAPI. This is achieved by using the `mount` method on a FastAPI instance, specifying the path prefix and the sub-application [2].\n\nFor example, you can create a main FastAPI application and a sub-application, then mount the sub-application under a specific path prefix:\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\nsubapi = FastAPI()\n\n# Mount subapi under the path prefix \"/subapi\"\napp.mount(\"/subapi\", subapi)\n```\nFastAPI will internally handle the `root_path` correctly, so it will just work as expected [1].\n\nHowever, there is a known limitation when trying to mount a sub-application under an `APIRouter`. Currently, it is not possible to mount a sub-application directly under an `APIRouter` using the `mount` method. The recommended approach is to mount the sub-application directly to the main FastAPI instance using the full path prefix [5].\n\nIt's also worth noting that when using a proxy with a stripped path prefix, you can configure your application using the `root_path` mechanism provided by the ASGI specification [4].", + "bc6e462cbbb9f553": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "0db98c89de011735": "FastAPI runs regular `def` endpoints without blocking the event loop by running them in an external threadpool that is then awaited [1]. \n\nHere's an example of how it's implemented in the code:\n```python\nasync def run_endpoint_function(\n *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool\n) -> Any:\n # Only called by get_request_handler. Has been split into its own function to\n # facilitate profiling endpoints, since inner functions are harder to profile.\n assert dependant.call is not None, \"dependant.call must be a function\"\n\n if is_coroutine:\n return await dependant.call(**values)\n else:\n return await run_in_threadpool(dependant.call, **values)\n```\nIn this code, if the endpoint function is not a coroutine (`is_coroutine` is `False`), it's run in a threadpool using `run_in_threadpool` [4]. \n\nIt's also mentioned in the documentation that:\n> When you declare a *path operation function* with normal `def` instead of `async def`, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server) [1]. \n\nThe same applies to dependencies. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool [1]. \n\nIt's recommended to use `async def` for endpoints and dependencies unless they use code that performs blocking I/O [1]. \n\nFor more information, you can also refer to [2].", + "a09a17dcb77999ad": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "ad5c7a5b30efd3ea": "To manage configuration and settings with environment variables in FastAPI, you can utilize Pydantic's `Settings` management feature. First, install the `pydantic-settings` package using pip:\n\n```console\n$ pip install pydantic-settings\n```\n\nor install the `all` extras with FastAPI:\n\n```console\n$ pip install \"fastapi[all]\"\n```\n\nNext, create a `Settings` object by importing `BaseSettings` from Pydantic and creating a sub-class. Declare class attributes with type annotations and possibly default values. Pydantic will read environment variables in a case-insensitive way, convert and validate the data, and provide it in the `settings` object [1].\n\nFor example, you can create a `config.py` file with:\n\n```python\nfrom pydantic import BaseSettings\n\nclass Settings(BaseSettings):\n admin_email: str\n app_name: str\n```\n\nThen, use the `settings` object in your application:\n\n```python\nfrom config import Settings\n\nsettings = Settings()\nprint(settings.admin_email)\nprint(settings.app_name)\n```\n\nYou can also provide settings from a dependency, which is useful during testing:\n\n```python\nfrom fastapi import Depends\nfrom config import Settings\n\ndef get_settings():\n return Settings()\n\n@app.get(\"/\")\ndef read_root(settings: Settings = Depends(get_settings)):\n return {\"message\": f\"Hello, {settings.app_name}!\"}\n```\n\nYou can put the settings in another module file and use it in your main application file. Additionally, using `@lru_cache` lets you avoid reading the dotenv file again and again for each request, while allowing you to override it during testing [2][4].", + "717dd6ee64695ff1": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "43169b6eb80b928a": "I couldn't find this in the indexed codebase.", + "d9206b7c65fe50ac": "```json\n{\n \"faithful\": true,\n \"correct\": false\n}\n```", + "4fb950074a232d5b": "The `OAuth2PasswordBearer` class is implemented in [1] (code: fastapi/security/oauth2.py). \n\nHere's a code snippet showing its definition:\n```python\nclass OAuth2PasswordBearer(OAuth2):\n \"\"\"\n OAuth2 flow for authentication using a bearer token obtained with a password.\n An instance of it would be used as a dependency.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n```", + "2c91f8cdb9dc57a3": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "a474db99da501229": "The `jsonable_encoder` function is implemented in [2] and [4].\n\nHere's a code snippet showing its definition [2]:\n```python\ndef jsonable_encoder(\n obj: Annotated[\n Any,\n Doc(\n \"\"\"\n The input object to convert to JSON.\n \"\"\"\n ),\n ],\n include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Pydantic's `include` parameter, passed to Pydantic models to set the\n fields to include.\n \"\"\"\n ),\n ] = None,\n exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Pydantic's `exclude` parameter, passed to Pydantic models to set the\n fields to exclude.\n \"\"\"\n ),\n ] = None,\n by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `by_alias` parameter, passed to Pydantic models to define if\n the output should use the alias names (when provided) or the Python\n attribute names. In an API, if you set an alias, it's probably because you\n want to use it in the result, so you probably want to leave this set to\n `True`.\n \"\"\"\n ),\n ] = True,\n exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_unset` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that were not explicitly\n set (and that only had their default values).\n \"\"\"\n ),\n ] = False,\n exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that had the same default\n value, even when they were explicitly set.\n \"\"\"\n ),\n ] = False,\n exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_none` parameter, passed to Pydantic models to define\n if it should exclude from the output any fields that have a `None` value.\n \"\"\"\n ),\n ] = False,\n custom_encoder: Annotated[\n dict[Any, Callable[[Any], Any]] | None,\n Doc(\n \"\"\"\n Pydantic's `custom_encoder` parameter, passed to Pydantic models to define\n a custom encoder.\n \"\"\"\n ),\n ] = None,\n sqlalchemy_safe: Annotated[\n bool,\n Doc(\n \"\"\"\n Exclude from the output any \n```", + "4e45d2db723405e8": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "f69ddb7ff5852c8a": "The `BackgroundTasks` class is defined in `fastapi/background.py` [4]. It is a subclass of `StarletteBackgroundTasks` and is imported directly into FastAPI to avoid confusion with the alternative `BackgroundTask` from `starlette.background` [1]. You can also import it directly from `fastapi` [3].", + "55f5778dbb32b93f": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "a52ff73d2c96733d": "The `HTTPException` in FastAPI is defined in `fastapi/exceptions.py` [1].", + "04bcfa239c0dcc5c": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "90e8b2e0c0c891a4": "The main FastAPI application class is defined in the `FastAPI` class, which can be imported directly from `fastapi`:\n\n```python\nfrom fastapi import FastAPI\n```\n\nYou can find more information about the `FastAPI` class, including its parameters, attributes, and methods, in the [FastAPI class documentation][2].", + "999112d2bd983ab9": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "77a656ab2a293e2e": "I couldn't find this in the indexed codebase.", + "b3c1c40cebbadc73": "```json\n{\n \"faithful\": true,\n \"correct\": false\n}\n```", + "54a7126b08e5c228": "The `TestClient` that FastAPI provides for testing is located in `fastapi.testclient`. You can import it directly as [1]:\n```python\nfrom fastapi.testclient import TestClient\n```\nIt is also available as `starlette.testclient.TestClient`, which FastAPI provides as a convenience [4]. \nIt is based on [HTTPX](https://www.python-httpx.org) and [Starlette](https://www.starlette.dev/testclient/).", + "583c827c369b02b1": "```json\n{\n \"faithful\": true,\n \"correct\": true\n}\n```", + "eb3f9da4d4490737": "I couldn't find this in the indexed codebase.", + "b09ae07b00fa37b0": "I couldn't find this in the indexed codebase.", + "d3fd9f6f6aecd452": "I couldn't find this in the indexed codebase.", + "d062da8f558229dd": "I couldn't find this in the indexed codebase.", + "304d836c813d1c6a": "I couldn't find this in the indexed codebase.", + "ec0de83acebf7550": "I couldn't find this in the indexed codebase.", + "be62f379bc41971e": "I couldn't find this in the indexed codebase." } \ No newline at end of file