Skip to content

Path parameters

You can declare path "parameters" with the same syntax used by Python format-strings (which luckily also matches the openapi path parameters):

def read_item(request, item_id):
    return {"item_id": item_id}

The value of the path parameter item_id will be passed to your function as the argument item_id.

So, if you run this example and go to http://localhost:8000/api/items/foo, you will see a response of:


Path parameters with types

You can declare the type of a path parameter in the function, using standard Python type annotations:

def read_item(request, item_id: int):
    return {"item_id": item_id}

In this case, item_id is declared to be an int. This will give you editor and linter support for error checks, completion, etc.

If you run this in your browser with http://localhost:8000/api/items/3, you will see a response of:



Notice that the value your function received (and returned) is 3, as a Python int, not a string "3". So, with just that type declaration, Django Ninja gives you automatic request "parsing" and validation.

Data validation

On the other hand if you go to the browser at http://localhost:8000/api/items/foo ("foo" is not int) you will see a HTTP error of:

    "detail": [
            "loc": [
            "msg": "value is not a valid integer",
            "type": "type_error.integer"

Multiple parameters

You can pass as many variables as you want variables into path, just keep in mind to have unique names and not forget to use same names in function arguments.

def events(request, year: int, month: int, day: int):
    return {"date": [year, month, day]}

Using Schema

You can as well use Schema to encapsulate path parameters that depend on each other (and validate them as a group)

import datetime
from ninja import Schema, Path

class PathDate(Schema):
    year: int
    month: int
    day: int

    def value(self):
        return, self.month,

def events(request, date: PathDate = Path(...)):
    return {"date": date.value()}


Notice that here we used a Path source hint to let Django Ninja know that this schema will be applied to path parameters.


And when you open your browser at http://localhost:8000/api/docs, you will see an automatic, interactive, API documentation like: Django Ninja Swagger