Skip to content

Commit 66ef30a

Browse files
committed
Added return type to response schema support to Ninja Router
1 parent 9f63bf2 commit 66ef30a

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

ninja_extra/router.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Callable, Dict, List, Optional
1+
from typing import Any, Callable, Dict, List, Optional, get_type_hints
22

33
from ninja.constants import NOT_SET
44
from ninja.router import Router as NinjaRouter
@@ -40,6 +40,10 @@ def add_api_operation(
4040
self.path_operations[path] = path_view
4141
else:
4242
path_view = self.path_operations[path]
43+
44+
if response is NOT_SET:
45+
response = get_type_hints(view_func).get("return") or NOT_SET
46+
4347
path_view.add_operation(
4448
path=path,
4549
methods=methods,

tests/test_django_ninja_router.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,29 @@
44
from ninja_extra import NinjaExtraAPI, Router
55
from ninja_extra.operation import PathView
66

7+
from .schemas import UserSchema
8+
79
api = NinjaExtraAPI(urls_namespace="ninja_router")
810

911

1012
@api.get("/endpoint")
1113
# view->api
12-
def global_op(request):
14+
def global_op(request) -> str:
1315
return "global"
1416

1517

18+
@api.get("/return_type_response")
19+
# view->api
20+
def return_type_response(request) -> UserSchema:
21+
return dict(name="Eadwin", age=20)
22+
23+
24+
@api.get("/return_type_response-2")
25+
# view->api
26+
def return_type_response(request) -> UserSchema:
27+
return UserSchema(name="Eadwin", age=20)
28+
29+
1630
first_router = Router()
1731

1832

@@ -105,3 +119,15 @@ def test_router_path_view():
105119
global_op_path_view = api.default_router.path_operations.get("/endpoint")
106120
assert router_op1_path_view
107121
assert isinstance(global_op_path_view, PathView)
122+
123+
124+
def test_return_response_type():
125+
res = client.get("/return_type_response")
126+
assert res.status_code == 200
127+
data = res.json()
128+
assert data == {"name": "Eadwin", "age": 20}
129+
130+
res = client.get("/return_type_response-2")
131+
assert res.status_code == 200
132+
data = res.json()
133+
assert data == {"name": "Eadwin", "age": 20}

0 commit comments

Comments
 (0)