Skip to content

Commit 6d7d0a4

Browse files
committed
docs: dynamic renderer documentation
1 parent 296cf2e commit 6d7d0a4

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

docs/docs/guides/response/response-renderers.md

+49-1
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,29 @@ api = NinjaAPI(renderer=MyRenderer())
2323

2424
The `render` method takes the following arguments:
2525

26-
- request -> HttpRequest object
26+
- request -> HttpRequest object
2727
- data -> object that needs to be serialized
2828
- response_status as an `int` -> the HTTP status code that will be returned to the client
2929

3030
You need also define the `media_type` attribute on the class to set the content-type header for the response.
3131

32+
## Rendering multiple content types
33+
34+
To create a renderer that will allow multiple different content types returned from the same API, you need to inherit `ninja.renderers.BaseDynamicRenderer` and override the `render` method. You still need to define the `media_type` but you can also define a list of prioritized media types within a `media_types` list. Like so:
35+
36+
```python hl_lines="5"
37+
from ninja import NinjaAPI
38+
from ninja.renderers import BaseDynamicRenderer
39+
40+
class MyDynamicRenderer(BaseDynamicRenderer):
41+
media_type = "application/json" # Default response content type
42+
media_types = ["application/json", "text/csv"]
43+
44+
def render(self, request, data, *, response_status):
45+
return ... # your custom serialization here
46+
47+
api = NinjaAPI(renderer=MyDynamicRenderer())
48+
```
3249

3350
## ORJSON renderer example:
3451

@@ -105,3 +122,34 @@ class XMLRenderer(BaseRenderer):
105122
api = NinjaAPI(renderer=XMLRenderer())
106123
```
107124
*(Copyright note: this code is basically copied from [DRF-xml](https://jpadilla.github.io/django-rest-framework-xml/))*
125+
126+
## JSON and CSV responses example:
127+
128+
This is how you can return JSON or a CSV based on passed headers:
129+
130+
```python hl_lines="4 8 15 21"
131+
from ninja import NinjaAPI
132+
from ninja.renderers import BaseDynamicRenderer
133+
134+
class DynamicRenderer(BaseDynamicRenderer):
135+
media_type = "application/json" # Default response content type
136+
media_types = ["application/json", "text/csv"]
137+
138+
def render(self, request, data, *, response_status):
139+
media_type = self.get_media_type(request)
140+
if media_type == "text/csv":
141+
return self.render_csv(data)
142+
143+
return self.render_json(data)
144+
145+
def render_csv(self, data):
146+
content = [",".join(data[0].keys())]
147+
for item in data:
148+
content.append(",".join(item.values()))
149+
return "\n".join(content)
150+
151+
def render_json(self, data):
152+
return json.dumps(data, cls=NinjaJSONEncoder)
153+
154+
api = NinjaAPI(renderer=DynamicRenderer())
155+
```

0 commit comments

Comments
 (0)