Tutorial - Handling input parameters
Passing parameters from the query string
Let's modify the operation to accept a name from the URL query string. To do this, simply add a name argument to our function.
@api.get("/hello")
def hello(request, name):
return f"Hello {name}"
When we provide the named argument, we get the expected (HTTP 200) response.
localhost:8000/api/hello?name=you:
"Hello you"
Default values
If you don't provide the parameter, an HTTP 422 error response is returned.
{
"detail": [
{
"loc": ["query", "name"],
"msg": "field required",
"type": "value_error.missing"
}
]
}
We can specify a default value for the name argument in case it is not provided:
@api.get("/hello")
def hello(request, name="world"):
return f"Hello {name}"
Input types
Django Ninja uses standard Python type hints to format input types. If no type is provided, string is assumed (but providing type hints for all arguments is best practice).
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
}
Passing parameters via path strings
You can declare path "parameters" using the same syntax as Python format strings.
Any parameter found in the path string will be passed to your function as an argument, instead of being taken 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 via localhost:8000/api/math/2and3.
Passing parameters via the request body
We will change the hello operation to use an HTTP POST request, and get the parameters from the request body.
To specify that parameters come from the request 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
Now accessing localhost:8000/api/hello will result in an HTTP 405 error response, because we need to change the request made to this URL to the POST type.
An easy way to do this is to use the Swagger documentation that is automatically created for us, at the default "/docs" URL (appended to our API URL root).
- Visit localhost:8000/api/docs to view the operations we created
- Open the
/api/hellooperation - Click "Try it out"
- Modify the request body
- Click "Execute"
Success
Continue to the next chapter Handling responses
Comments
本文总阅读量次
