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.

@api.get("/hello")
def hello(request, name):
    return f"Hello {name}"

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

localhost:8000/api/hello?name=you:

"Hello you"

Defaults

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

localhost:8000/api/hello:

{
  "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:

@api.get("/hello")
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.

@api.get("/hello")
def hello(request, name: str = "world"):
    return f"Hello {name}"

@api.get("/math")
def math(request, a: int, b: int):
    return {"add": a + b, "multiply": a * b}

localhost:8000/api/math?a=2&b=3:

{
  "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.

@api.get("/math/{a}and{b}")
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"

@api.post("/hello")
def hello(request, data: HelloSchema):
    return f"Hello {data.name}"

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"

Success

Continue on to Handling responses