查询参数
修改api.py,接受一个name查询参数:
from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/hello")
def hello(request, name: str = "张大鹏"):
# 这里的name是查询参数
return f"你好 {name}"
浏览器访问:http://127.0.0.1:8000/api/hello?name=%E5%BC%A0%E4%B8%89
路径参数
修改api.py,接受两个整数类型的路径参数a和b:
from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/math/{a}/{b}")
def math(request, a: int, b: int):
return {"相加": a + b, "相乘": a * b}
浏览器访问:http://127.0.0.1:8000/api/math/3/8
JSON参数
修改api.py,通过Schema定义json参数:
from ninja import NinjaAPI, Schema
api = NinjaAPI()
class HelloSchema(Schema):
name: str = "张大鹏"
@api.post("/hello")
def hello(request, data: HelloSchema):
return f"你好 {data.name}"
浏览器访问:http://127.0.0.1:8000/api/docs,通过接口文档执行接口请求。
JSON响应
修改api.py,定义响应类型并返回响应:
from ninja import NinjaAPI, Schema
api = NinjaAPI()
class UserSchema(Schema):
id: int = 1
name: str = "张大鹏"
@api.post("/hello", response=UserSchema)
def hello(request):
# 返回的参数要和schema对应
return {
"id": 22,
"name": "张三"
}
多种JSON响应
from ninja import NinjaAPI, Schema
api = NinjaAPI()
class UserSchema(Schema):
id: int = 1
name: str = "张大鹏"
class Error(Schema):
message: str
@api.post("/hello", response={200: UserSchema, 403: Error})
def hello(request, status: int = 1):
# 错误响应
if status != 1:
return 403, {"message": "错误的响应"}
# 正常响应
return {
"id": 22,
"name": "张三"
}
本文使用 markdown.com.cn 排版