-
Is it possible to set headers for the response schema? There's |
Beta Was this translation helpful? Give feedback.
Answered by
vitalik
Sep 22, 2025
Replies: 1 comment 1 reply
-
Hi @Nekidev - well not out of the box for the moment - but you can use
here is a quick code on how to convet schema to openapi responses: import random
from ninja import NinjaAPI, Schema, Field
from django.http import HttpRequest, HttpResponse
class NumberResponse(Schema):
value: int
class HelloHeaders(Schema):
x_hello: str = Field(..., alias="X-hello", description="Static greeting value returned on every call.")
api = NinjaAPI()
def _schema_to_openapi(schema):
"""Creates an OpenAPI-compatible headers block from a Ninja/Pydantic schema."""
properties = schema.model_json_schema(by_alias=True).get("properties", {})
headers = {}
for name, definition in properties.items():
definition = dict(definition)
description = definition.pop("description", None)
headers[name] = {"schema": definition}
if description:
headers[name]["description"] = description
return headers
HELLO_HEADERS_OPENAPI = _schema_to_openapi(HelloHeaders)
@api.get(
"/number/random",
response=NumberResponse,
openapi_extra={"responses": {200: {"headers": HELLO_HEADERS_OPENAPI}}},
)
def random_number(request: HttpRequest, response: HttpResponse):
number = random.randint(0, 100)
response['X-hello'] = 'greetings'
return {'value': number}
@api.post(
"/number",
response={204: None},
openapi_extra={"responses": {204: {"headers": HELLO_HEADERS_OPENAPI}}},
)
def create_number(request: HttpRequest, response: HttpResponse):
response['X-hello'] = 'greetings'
return 'created' |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
Nekidev
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @Nekidev - well not out of the box for the moment - but you can use
openapi_extra
to pass headers schema:here is a quick code on how to convet schema to openapi responses: