Skip to content

Tutorial - Parsing Input

Input from the query string

Let's change our operation to accept a name from the URL's query string. To do that, just add a name argument to our function.

def hello(request, name):
    return f"Hello {name}"

When we provide a name argument, we get the expected (HTTP 200) response.


"Hello you"


Not providing the argument will return an HTTP 422 error response.


  "detail": [
      "loc": ["query", "name"],
      "msg": "field required",
      "type": "value_error.missing"

We can specify a default for the name argument in case it isn't provided:

def hello(request, name="world"):
    return f"Hello {name}"

Input types

Django Ninja uses standard Python type hints to format the input types. If no type is provided then a string is assumed (but it is good practice to provide type hints for all your arguments).

Let's add a second operation that does some basic math with integers.

def hello(request, name: str = "world"):
    return f"Hello {name}"

def math(request, a: int, b: int):
    return {"add": a + b, "multiply": a * b}


  "add": 5,
  "multiply": 6

Input from the path

You can declare path "parameters" with the same syntax used by Python format-strings.

Any parameters found in the path string will be passed to your function as arguments, rather than expecting them from the query string.

def math(request, a: int, b: int):
    return {"add": a + b, "multiply": a * b}

Now we access the math operation from localhost:8000/api/math/2and3.

Input from the request body

We are going to change our hello operation to use HTTP POST instead, and take arguments from the request body.

To specify that arguments come from the body, we need to declare a Schema.

from ninja import NinjaAPI, Schema

api = NinjaAPI()

class HelloSchema(Schema):
    name: str = "world""/hello")
def hello(request, data: HelloSchema):
    return f"Hello {}"

Self-documenting API

Accessing localhost:8000/api/hello now results in a HTTP 405 error response, since we need to POST to this URL instead.

An easy way to do this is to use the Swagger documentation that is automatically created for us, at default URL of "/docs" (appended to our API url root).

  1. Visit localhost:8000/api/docs to see the operations we have created
  2. Open the /api/hello operation
  3. Click "Try it out"
  4. Change the request body
  5. Click "Execute"


Continue on to Handling responses