Skip to content

Conversation

skokado
Copy link
Contributor

@skokado skokado commented Oct 1, 2025

Hi, I'm very greateful this project!

I ran into a few issues when trying to use custom headers.

First, the function argument my_header defined as follows didn't work no matter what I did.

from ninja import Header

@api.get("")
def events(request, my_header: Header[str]):
    return {"received": my_header}

I got a 422 status code.

$ curl -H 'my_header: abc' localhost:8000 
{
  "detail": [
    {
      "type": "missing",
      "loc": [
        "header",
        "my_header"
      ],
      "msg": "Field required"
    }
  ]
}

To resolve this, I had to use an alias to separate the header name with hyphens.

@api.get("")
def events(request, my_header: str = Header(alias="my-header"):
    return {"received": my_header}
$ curl -H 'my-header: abc' localhost:8000
{"received": "abc"}

I also discovered a "mypy cheat" block in ninja.params.
This causes Header to always be annotated in the editor, which causes Header() to issue a warning.
I'm not entirely sure why "mypy cheat" is necessary today, but it at least seems to work.

image

I've also added documentation based on the issues I encountered.

Personally, I think it would be better to expect similar usage for parameters like Query and Path in ninja.params, but I won't make any changes in this PR.

@skokado skokado force-pushed the improve-header-param-usage-and-doc branch from dcd1a87 to 3ce6f21 Compare October 1, 2025 14:04
@skokado skokado marked this pull request as ready for review October 1, 2025 14:07
@skokado skokado changed the title Add guide for using request headers and improve type hints Add guide for using Request Header and improve type hints usage Oct 1, 2025
@skokado
Copy link
Contributor Author

skokado commented Oct 1, 2025

A little more information:

I added the hyphenated alias example because I was considering integration with OpenAPI.

By default, the header name would be in snake case, which would result in a 422 response, which I thought might confuse developers.

When alias not set for argument my_header, the header name in OpenAPI also would be my_header

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant