]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
📝 Add docs for creating a custom Response class (#5331)
authorSebastián Ramírez <tiangolo@gmail.com>
Thu, 1 Sep 2022 09:32:30 +0000 (11:32 +0200)
committerGitHub <noreply@github.com>
Thu, 1 Sep 2022 09:32:30 +0000 (09:32 +0000)
docs/en/docs/advanced/custom-response.md
docs_src/custom_response/tutorial009c.py [new file with mode: 0644]
tests/test_tutorial/test_custom_response/test_tutorial009c.py [new file with mode: 0644]

index 546adad2a194584a0393ba6b275761e62d4c15f7..3ca47bf3b8a5c227ae065ec03fddd9aca7c6c8e9 100644 (file)
@@ -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.
diff --git a/docs_src/custom_response/tutorial009c.py b/docs_src/custom_response/tutorial009c.py
new file mode 100644 (file)
index 0000000..de6b668
--- /dev/null
@@ -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"}
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial009c.py b/tests/test_tutorial/test_custom_response/test_tutorial009c.py
new file mode 100644 (file)
index 0000000..23c711a
--- /dev/null
@@ -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}'