Debian Codegraph @

docs/usage.rst

raw
1 .. _usage:
2
3 Usage
4 =====
5
6 Quickstart
7 ----------
8
9 .. note::
10 Using strict=True need only for marshmallow < 3.0.0
11
12 .. code-block:: python
13
14 from aiohttp_apispec import (docs,
15 request_schema,
16 response_schema,
17 setup_aiohttp_apispec)
18 from aiohttp import web
19 from marshmallow import Schema, fields
20
21
22 class RequestSchema(Schema):
23 id = fields.Int()
24 name = fields.Str(description='name')
25 bool_field = fields.Bool()
26
27
28 class ResponseSchema(Schema):
29 msg = fields.Str()
30 data = fields.Dict()
31
32
33 @docs(tags=['mytag'],
34 summary='Test method summary',
35 description='Test method description')
36 @request_schema(RequestSchema(strict=True))
37 @response_schema(ResponseSchema(), 200)
38 async def index(request):
39 return web.json_response({'msg': 'done',
40 'data': {}})
41
42 # Class based views are also supported:
43 class TheView(web.View):
44 @docs(
45 tags=['mytag'],
46 summary='View method summary',
47 description='View method description',
48 )
49 @request_schema(RequestSchema(strict=True))
50 def delete(self):
51 return web.json_response({
52 'msg': 'done',
53 'data': {'name': self.request['data']['name']},
54 })
55
56
57 app = web.Application()
58 app.router.add_post('/v1/test', index)
59 app.router.add_view('/v1/view', TheView)
60
61 # init docs with all parameters, usual for ApiSpec
62 setup_aiohttp_apispec(app=app, title="My Documentation", version="v1")
63
64
65 # find it on 'http://localhost:8080/api/docs/api-docs'
66 web.run_app(app)
67
68 Adding validation middleware
69 ----------------------------
70
71 .. code-block:: python
72
73 from aiohttp_apispec import validation_middleware
74
75 ...
76
77 app.middlewares.append(validation_middleware)
78
79 Now you can access all validated data in route from ``request['data']`` like so:
80
81 .. code-block:: python
82
83 @docs(tags=['mytag'],
84 summary='Test method summary',
85 description='Test method description')
86 @request_schema(RequestSchema(strict=True))
87 @response_schema(ResponseSchema(), 200)
88 async def index(request):
89 uid = request['data']['id']
90 name = request['data']['name']
91 return web.json_response(
92 {'msg': 'done',
93 'data': {'info': f'name - {name}, id - {uid}'}}
94 )
95
96 You can change ``Request``'s ``'data'`` param to another
97 with ``request_data_name`` argument of ``setup_aiohttp_apispec`` function:
98
99 .. code-block:: python
100
101 setup_aiohttp_apispec(app=app,
102 request_data_name='validated_data',
103 title='My Documentation',
104 version='v1',
105 url='/api/docs/api-docs')
106
107 ...
108
109 @request_schema(RequestSchema(strict=True))
110 async def index(request):
111 uid = request['validated_data']['id']
112 ...
113
114 More decorators
115 ---------------
116
117 Starting from version 2.0 you can use shortenings for documenting and validating
118 specific request parts like cookies, headers etc using those decorators:
119
120 ================== =======================
121 Decorator name Default put_into param
122 ================== =======================
123 match_info_schema match_info
124 querystring_schema querystring
125 form_schema form
126 json_schema json
127 headers_schema headers
128 cookies_schema cookies
129 ================== =======================
130
131 And example:
132
133 .. code-block:: python
134
135 @docs(
136 tags=["users"],
137 summary="Create new user",
138 description="Add new user to our toy database",
139 responses={
140 200: {"description": "Ok. User created", "schema": OkResponse},
141 401: {"description": "Unauthorized"},
142 422: {"description": "Validation error"},
143 500: {"description": "Server error"},
144 },
145 )
146 @headers_schema(AuthHeaders)
147 @json_schema(UserMeta)
148 @querystring_schema(UserParams)
149 async def create_user(request: web.Request):
150 headers = request["headers"] # <- validated headers!
151 json_data = request["json"] # <- validated json!
152 query_params = request["querystring"] # <- validated querystring!
153 ...
154
155
156 Custom error handling
157 ---------------------
158
159 If you want to catch validation errors by yourself you
160 could use ``error_callback`` parameter and create your custom error handler. Note that
161 it can be one of coroutine or callable and it should
162 have interface exactly like in examples below:
163
164 .. code-block:: python
165
166 from marshmallow import ValidationError, Schema
167 from aiohttp import web
168 from typing import Optional, Mapping, NoReturn
169
170
171 def my_error_handler(
172 error: ValidationError,
173 req: web.Request,
174 schema: Schema,
175 error_status_code: Optional[int] = None,
176 error_headers: Optional[Mapping[str, str]] = None,
177 ) -> NoReturn:
178 raise web.HTTPBadRequest(
179 body=json.dumps(error.messages),
180 headers=error_headers,
181 content_type="application/json",
182 )
183
184 setup_aiohttp_apispec(app, error_callback=my_error_handler)
185
186 Also you can create your own exceptions and create
187 regular Request in middleware like so:
188
189 .. code-block:: python
190
191 class MyException(Exception):
192 def __init__(self, message):
193 self.message = message
194
195 # It can be coroutine as well:
196 async def my_error_handler(
197 error: ValidationError,
198 req: web.Request,
199 schema: Schema,
200 error_status_code: Optional[int] = None,
201 error_headers: Optional[Mapping[str, str]] = None,
202 ) -> NoReturn:
203 await req.app["db"].do_smth() # So you can use some async stuff
204 raise MyException({"errors": error.messages, "text": "Oops"})
205
206 # This middleware will handle your own exceptions:
207 @web.middleware
208 async def intercept_error(request, handler):
209 try:
210 return await handler(request)
211 except MyException as e:
212 return web.json_response(e.message, status=400)
213
214
215 setup_aiohttp_apispec(app, error_callback=my_error_handler)
216
217 # Do not forget to add your own middleware before validation_middleware
218 app.middlewares.extend([intercept_error, validation_middleware])
219
220 Named routes
221 ------------
222
223 Routes for the Swagger UI and to the swagger specification file `swagger.json`
224 are registered as `named resources <https://docs.aiohttp.org/en/stable/web_quickstart.html#reverse-url-constructing-using-named-resources`_
225 with the `swagger.docs` and `swagger.spec` names respectively. The
226 corresponding routes are therefore avaialble un the value returned by the
227 application's router `named_resources()` call.
228
229
230 Build swagger web client
231 ------------------------
232
233 3.X SwaggerUI version
234 *********************
235
236
237 Just add ``swagger_path`` parameter to ``setup_aiohttp_apispec`` function.
238
239 For example:
240
241 .. code-block:: python
242 setup_aiohttp_apispec(app, swagger_path="/docs")
243
244 Then go to ``/docs`` and see awesome SwaggerUI
245
246 2.X SwaggerUI version
247 *********************
248
249 ``aiohttp-apispec`` adds ``swagger_dict`` parameter to aiohttp
250 web application after initialization (with ``setup_aiohttp_apispec`` function).
251 So you can use it easily with ``aiohttp_swagger`` library:
252
253 .. code-block:: python
254
255 from aiohttp_apispec import setup_aiohttp_apispec
256 from aiohttp_swagger import setup_swagger
257
258
259 def create_app(app):
260 setup_aiohttp_apispec(app)
261
262 async def swagger(app):
263 setup_swagger(
264 app=app, swagger_url='/api/doc', swagger_info=app['swagger_dict']
265 )
266 app.on_startup.append(swagger)
267 # now we can access swagger client on '/api/doc' url
268 ...
269 return app
270
271 Now we can access swagger client on ``/api/doc`` url