Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/en/docs/advanced/custom-response.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,36 @@ You can also use the `response_class` parameter:

In this case, you can return the file path directly from your *path operation* function.

## Custom response class

You can create your own custom response class, inheriting from `Response` and using it.

For example, let's say that you want to use <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a>, but with some custom settings not used in the included `ORJSONResponse` class.

Let's say you want it to return indented and formatted JSON, so you want to use the orjson option `orjson.OPT_INDENT_2`.

You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`:

```Python hl_lines="9-14 17"
{!../../../docs_src/custom_response/tutorial009c.py!}
```

Now instead of returning:

```json
{"message": "Hello World"}
```

...this response will return:

```json
{
"message": "Hello World"
}
```

Of course, you will probably find much better ways to take advantage of this than formatting JSON. πŸ˜‰

## Default response class

When creating a **FastAPI** class instance or an `APIRouter` you can specify which response class to use by default.
Expand Down
19 changes: 19 additions & 0 deletions docs_src/custom_response/tutorial009c.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from typing import Any

import orjson
from fastapi import FastAPI, Response

app = FastAPI()


class CustomORJSONResponse(Response):
media_type = "application/json"

def render(self, content: Any) -> bytes:
assert orjson is not None, "orjson must be installed"
return orjson.dumps(content, option=orjson.OPT_INDENT_2)


@app.get("/", response_class=CustomORJSONResponse)
async def main():
return {"message": "Hello World"}
10 changes: 10 additions & 0 deletions tests/test_tutorial/test_custom_response/test_tutorial009c.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from fastapi.testclient import TestClient

from docs_src.custom_response.tutorial009c import app

client = TestClient(app)


def test_get():
response = client.get("/")
assert response.content == b'{\n "message": "Hello World"\n}'