new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

FastAPI · Advanced · all subjects

responses

52 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

JSONResponse and status available from fastapi.responses

FastAPI provides JSONResponse and status through fastapi.responses for convenience, which are re-exported from Starlette. You can also import directly from starlette.responses if preferred.

Direct Response returns are not serialized

When you return a Response directly (such as JSONResponse), it will be returned as-is without being serialized with a model. You must ensure the response has the correct data already prepared and that values are valid for the response type.

Override default JSON response with response_class parameter

By default, FastAPI returns JSON responses. You can override this by declaring the Response class you want to use in the path operation decorator using the response_class parameter. The contents returned from the path operation function will be put inside that Response.

Response class without media type expects no content

If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.

Returning Response directly bypasses OpenAPI documentation

A Response returned directly by your path operation function won't be documented in OpenAPI (for example, the Content-Type won't be documented) and won't be visible in the automatic interactive docs. However, the actual Content-Type header, status code, and other properties will come from the Response object you returned.

Combine response_class parameter with direct Response return for OpenAPI documentation

If you want to override the response from inside the function but also document the media type in OpenAPI, use the response_class parameter AND return a Response object. The response_class will be used only to document the OpenAPI path operation, while your Response will be used as is.

Response class parameters

The Response class accepts the following parameters: content (a str or bytes), status_code (an int HTTP status code), headers (a dict of strings), and media_type (a str giving the media type, e.g. 'text/html'). FastAPI will automatically include a Content-Length header and a Content-Type header based on the media_type, appending a charset for text types.

HTMLResponse for HTML responses

To return a response with HTML directly from FastAPI, use HTMLResponse. Import HTMLResponse and pass it as the response_class parameter of your path operation decorator. The HTTP header Content-Type will be set to text/html and it will be documented as such in OpenAPI.

PlainTextResponse for plain text responses

PlainTextResponse takes some text or bytes and returns a plain text response with the appropriate media type.

JSONResponse for JSON encoded responses

JSONResponse takes some data and returns an application/json encoded response. This is the default response used in FastAPI. However, if you declare a response model or return type, that will be used directly to serialize the data to JSON without using the JSONResponse class, which is the ideal way to get the best performance.

RedirectResponse for HTTP redirects

RedirectResponse returns an HTTP redirect. It uses a 307 status code (Temporary Redirect) by default. You can return a RedirectResponse directly or use it in the response_class parameter. When used in response_class, you can return the URL directly from your path operation function. You can also combine the status_code parameter with the response_class parameter to specify a different status code.

StreamingResponse for streaming responses

StreamingResponse takes an async generator or a normal generator/iterator (a function with yield) and streams the response body. For proper cancellation handling with generators that have no await statements, add an await anyio.sleep(0) to give the event loop a chance to handle cancellation. For convenience and automatic cancellation handling, follow the Stream Data style instead of returning StreamingResponse directly.

FileResponse for file streaming

FileResponse asynchronously streams a file as the response. It takes the following parameters: path (the file path to stream), headers (any custom headers to include as a dictionary), media_type (a string giving the media type; if unset, the filename or path will be used to infer it), and filename (if set, this will be included in the response Content-Disposition). FileResponse will automatically include appropriate Content-Length, Last-Modified, and ETag headers. You can also use it with the response_class parameter to return the file path directly from your path operation function.

Create custom response class by inheriting from Response

You can create your own custom response class by inheriting from Response. The main requirement is to implement a Response.render(content) method that returns the content as bytes. This allows you to customize response serialization, such as using orjson with specific settings.

Response model preferred over custom response classes for performance

For performance optimization, using a Response Model is better than creating a custom response class like an orjson response. With a response model, FastAPI uses Pydantic to serialize data to JSON without intermediate steps like jsonable_encoder. Pydantic uses the same underlying Rust mechanisms as orjson, so you get the best performance with a response model.

Set default response class with default_response_class parameter

When creating a FastAPI class instance or an APIRouter, you can specify which response class to use by default using the default_response_class parameter. This will use the specified response class in all path operations instead of the default JSON response. You can still override response_class in individual path operations.

JSON performance with response model

For maximum JSON performance, use a Response Model and do not declare a response_class in the path operation decorator. When you declare a response model, FastAPI will use it to serialize the data to JSON directly using Pydantic, which is the ideal way to get the best performance.

JSONResponse with declared response_class converts data automatically

If you declare a response_class with a JSON media type (application/json) like JSONResponse, the data you return will be automatically converted and filtered with any Pydantic response_model declared in the path operation decorator. The data will be converted with jsonable_encoder and then passed to the JSONResponse class, which will serialize it to bytes using the standard JSON library in Python.

Use Response parameter to change status code in path operation

You can declare a parameter of type Response in a path operation function to set the status code dynamically. Use response.status_code to set the HTTP status code on that temporary response object. FastAPI will extract the status code from this temporary response and use it in the final response, along with any filtering from response_model.

Status code from Response parameter overrides default

When you use a Response parameter to set status_code, you can return different status codes than the default set on the path operation. This is useful for cases like returning 200 OK by default but 201 CREATED when creating new data.

Response parameter works with response_model filtering

When you declare a Response parameter and set its status_code, the response_model is still applied to filter and convert the returned object. FastAPI uses the temporary response to extract the status code and combines it with the filtered response model value.

Response parameter can be set in dependencies

You can declare a Response parameter in dependencies as well as in path operation functions to set the status code. If multiple dependencies set the status code, the last one to be set will win.

Response parameter works with response_model

If you declare a response_model on your path operation, it will still filter and convert the object you return, even when you use a Response parameter to set cookies and headers.

Declare Response parameter for cookies

You can declare a parameter of type Response in your path operation function to set cookies. FastAPI uses this temporary response object to extract cookies, headers, and status code, then puts them in the final response that contains the value you returned.

Declare Response parameter in dependencies for cookies

You can declare a Response parameter in dependencies to set cookies and headers, not just in path operation functions.

Return Response directly for cookies

You can create and return a Response directly in your path operation to set cookies. When you return a Response directly, FastAPI returns it as-is, so you must ensure the data is the correct type and compatible with the response format.

Pitfall: returning Response directly bypasses response_model

If you return a Response directly instead of using the Response parameter, FastAPI returns it directly without applying response_model filtering. You must ensure your data is of the correct type and not sending data that should have been filtered by response_model.

FastAPI Response convenience import

FastAPI provides Response at fastapi.Response as a convenience, in addition to the import from starlette.responses. You can import Response from either fastapi or starlette.responses.

Custom header naming conventions

Custom proprietary headers can be added using the X- prefix. However, if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations using the expose_headers parameter documented in Starlette's CORS docs.

Adding headers when returning Response directly

You can add headers when returning a Response directly by passing headers as an additional parameter when creating the response object.

Setting headers with Response parameter in dependencies

You can declare a Response parameter in dependencies to set headers and cookies. FastAPI will extract these from the temporary response object used in the dependency.

Setting headers with Response parameter in path operation

You can declare a parameter of type Response in your path operation function to set headers in a temporary response object. FastAPI will extract the headers from this temporary response and place them in the final response along with the returned value. If a response_model is declared, it will still filter and convert the returned object. This works the same way as setting cookies and status codes.

Response Model provides better performance than JSONResponse

You will normally have much better performance using a Response Model than returning a JSONResponse directly, because the Response Model serializes the data using Pydantic in Rust.

XMLResponse or custom Response example

You can return a custom response by putting your content in a string and wrapping it in a Response with the appropriate media type. For example, you could return an XML response by putting XML content in a string, putting that in a Response with media type text/xml, and returning it.

Default behavior without Response Model or Response

When you don't declare a Response Model and don't return a Response directly, FastAPI will use jsonable_encoder and put the result in a JSONResponse.

fastapi.responses provides starlette.responses as convenience

FastAPI provides starlette.responses as fastapi.responses as a convenience for developers. Most of the available responses come directly from Starlette.

Return a Response directly instead of a model

When you return a Response or any sub-class of it directly from a path operation, FastAPI passes it directly without any data conversion with Pydantic models or conversion of contents to any type. This gives you flexibility to return any data type and override any data declaration or validation, but you are responsible for making sure the data you return is correct, in the correct format, and can be serialized.

JSONResponse is a subclass of Response

JSONResponse itself is a sub-class of Response and can be returned directly from a path operation.

Use jsonable_encoder to convert data before putting in Response

Because FastAPI does not make any changes to a Response you return, you cannot put a Pydantic model in a JSONResponse without first converting it to a dict with all data types like datetime and UUID converted to JSON-compatible types. You can use jsonable_encoder to convert your data before passing it to a response.

Response Model serialization uses Pydantic in Rust for better performance

When you declare a Response Model in a path operation, FastAPI will use it to serialize the data to JSON using Pydantic. This serialization happens on the Rust side which provides much better performance than using JSONResponse directly. FastAPI won't use jsonable_encoder or JSONResponse class when using a response_model or return type; instead it takes the JSON bytes generated with Pydantic using the response model and returns a Response with the right media type for JSON directly.

Returning a Response directly disables automatic validation and documentation

When you return a Response directly, its data is not validated, converted (serialized), or documented automatically. However, you can still document it as described in Additional Responses in OpenAPI.

StreamingResponse with yield for streaming pure binary data

To stream pure binary data or strings in FastAPI, declare response_class=StreamingResponse in your path operation function and use yield to send each chunk of data in turn. FastAPI will pass each chunk to StreamingResponse as-is without attempting JSON conversion.

StreamingResponse supports non-async path operation functions

You can use regular def functions without async and still use yield with StreamingResponse to stream data chunks.

StreamingResponse does not require return type annotation

With StreamingResponse, you don't need to declare a return type annotation for streaming binary data. The type annotation is only for editor and tools; FastAPI will not use it. You have the freedom and responsibility to produce and encode the data bytes exactly as needed.

Stream bytes with StreamingResponse

You can stream bytes instead of strings by yielding bytes objects in your path operation function with response_class=StreamingResponse.

Custom StreamingResponse subclass for Content-Type header

You can create a custom sub-class of StreamingResponse to set the Content-Type header. Use the media_type attribute to specify the content type, such as media_type='image/png' for PNG data.

File-like objects and async compatibility

Most file-like objects are not compatible with async and await by default. Reading them is often a blocking operation that could block the event loop. To avoid blocking the event loop when working with file-like objects, declare the path operation function with regular def instead of async def, so FastAPI will run it on a threadpool worker.

Use with block to close file-like objects in generator functions

When using a file-like object in a generator function with yield, use a with block to ensure the file-like object is closed after the generator function completes, which happens after the response finishes sending.

io.BytesIO for in-memory file-like objects

io.BytesIO creates a file-like object that lives only in memory and supports iteration to consume its contents. It provides the same interface as a file but does not have blocking I/O operations since the data is already in memory.

StreamingResponse added in FastAPI 0.134.0

The StreamingResponse feature for streaming pure binary data and strings was added in FastAPI 0.134.0.

StreamingResponse use cases

StreamingResponse can be used to stream pure strings from AI LLM service outputs, stream large binary files in chunks without loading all into memory at once, and stream video or audio content that may be generated during processing.

yield from syntax for streaming iterables

When iterating over something like a file-like object and yielding each item, you can use yield from to yield each item directly and skip the for loop.

Give your agent this brain