-
-
Notifications
You must be signed in to change notification settings - Fork 6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
馃摑 Add docs for creating a custom Response class (#5331)
- Loading branch information
Showing
3 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
10
tests/test_tutorial/test_custom_response/test_tutorial009c.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}' |