![]() ![]() Here are some of the available responses. In this example, the function generate_html_response() already generates and returns a Response instead of returning the HTML in a str.īy returning the result of calling generate_html_response(), you are already returning a Response that will override the default FastAPI behavior.īut as you passed the HTMLResponse in the response_class too, FastAPI will know how to document it in OpenAPI and the interactive docs as HTML with text/html: get ( "/items/", response_class = HTMLResponse ) async def read_items (): return generate_html_response () This is what allows you to return arbitrary objects, for example database models.īut if you are certain that the content that you are returning is serializable with JSON, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the jsonable_encoder before passing it to the response class.įrom fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI () def generate_html_response (): html_content = """ Some HTML in here Look ma! HTML! """ return HTMLResponse ( content = html_content, status_code = 200 ). This is because by default, FastAPI will inspect every item inside and make sure it is serializable with JSON, using the same JSON Compatible Encoder explained in the tutorial. Import the Response class (sub-class) you want to use and declare it in the path operation decorator.įor large responses, returning a Response directly is much faster than returning a dictionary. Use ORJSONResponse ¶įor example, if you are squeezing performance, you can install and use orjson and set the response to be ORJSONResponse. 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. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |