Skip to content

Commit

Permalink
馃摑 Add docs for creating a custom Response class (#5331)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiangolo committed Sep 1, 2022
1 parent b9d7f86 commit 356a57d
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
30 changes: 30 additions & 0 deletions docs/en/docs/advanced/custom-response.md
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
@@ -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
@@ -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}'

0 comments on commit 356a57d

Please sign in to comment.