| 1 | <h1 align="center">aiohttp-apispec</h1> |
| 2 | <p align="center">Build and document REST APIs with <a href="https://github.com/aio-libs/aiohttp">aiohttp</a> and <a href="https://github.com/marshmallow-code/apispec">apispec</a></p> |
| 3 | |
| 4 | <p align="center"> |
| 5 | <a href="https://pypi.python.org/pypi/aiohttp-apispec"><img src="https://badge.fury.io/py/aiohttp-apispec.svg" alt="Pypi"></a> |
| 6 | <a href="https://github.com/maximdanilchenko/aiohttp-apispec/graphs/contributors"><img src="https://img.shields.io/github/contributors/maximdanilchenko/aiohttp-apispec.svg" alt="Contributors"></a> |
| 7 | <a href="https://pepy.tech/project/aiohttp-apispec"><img src="https://pepy.tech/badge/aiohttp-apispec" alt="Downloads"></a> |
| 8 | </p> |
| 9 | |
| 10 | <p align="center"> |
| 11 | <a href="https://app.travis-ci.com/github/maximdanilchenko/aiohttp-apispec"><img src="https://app.travis-ci.com/maximdanilchenko/aiohttp-apispec.svg?branch=master" alt="build status"></a> |
| 12 | <a href="https://aiohttp-apispec.readthedocs.io/en/latest/?badge=latest"><img src="https://readthedocs.org/projects/aiohttp-apispec/badge/?version=latest" alt="[docs]"></a> |
| 13 | <a href="https://codecov.io/gh/maximdanilchenko/aiohttp-apispec"><img src="https://codecov.io/gh/maximdanilchenko/aiohttp-apispec/branch/master/graph/badge.svg" alt="[codcov]"></a> |
| 14 | <a href="https://github.com/ambv/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code style: black"></a> |
| 15 | </p> |
| 16 | |
| 17 | <p> |
| 18 | |
| 19 | ```aiohttp-apispec``` key features: |
| 20 | - ```docs``` and ```request_schema``` decorators |
| 21 | to add swagger spec support out of the box; |
| 22 | - ```validation_middleware``` middleware to enable validating |
| 23 | with marshmallow schemas from those decorators; |
| 24 | - **SwaggerUI** support. |
| 25 | - *New from version 2.0* - ```match_info_schema```, ```querystring_schema```, |
| 26 | ```form_schema```, ```json_schema```, ```headers_schema``` and ```cookies_schema``` |
| 27 | decorators for specific request parts validation. |
| 28 | Look [here](#more-decorators) for more info. |
| 29 | |
| 30 | ```aiohttp-apispec``` api is fully inspired by ```flask-apispec``` library |
| 31 | |
| 32 | **Version 3.0.0b1 with apispec>=5.0 webargs>=8.0 is in beta now** (`pip install aiohttp-apispec==3.0.0b1`). |
| 33 | |
| 34 | ## Contents |
| 35 | |
| 36 | - [Install](#install) |
| 37 | - [Quickstart](#quickstart) |
| 38 | - [Adding validation middleware](#adding-validation-middleware) |
| 39 | - [More decorators](#more-decorators) |
| 40 | - [Custom error handling](#custom-error-handling) |
| 41 | - [Build swagger web client](#build-swagger-web-client) |
| 42 | - [Versioning](#versioning) |
| 43 | |
| 44 | |
| 45 | ## Install |
| 46 | |
| 47 | ``` |
| 48 | pip install aiohttp-apispec |
| 49 | ``` |
| 50 | |
| 51 | ## Quickstart |
| 52 | |
| 53 | *Also you can read [blog post](https://dmax.blog/how_to_easily_build_modern_web_apis_with_python_and_aiohttp) about quickstart with aiohttp-apispec* |
| 54 | |
| 55 | ```Python |
| 56 | from aiohttp_apispec import ( |
| 57 | docs, |
| 58 | request_schema, |
| 59 | setup_aiohttp_apispec, |
| 60 | ) |
| 61 | from aiohttp import web |
| 62 | from marshmallow import Schema, fields |
| 63 | |
| 64 | |
| 65 | class RequestSchema(Schema): |
| 66 | id = fields.Int() |
| 67 | name = fields.Str(description="name") |
| 68 | |
| 69 | @docs( |
| 70 | tags=["mytag"], |
| 71 | summary="Test method summary", |
| 72 | description="Test method description", |
| 73 | ) |
| 74 | @request_schema(RequestSchema(strict=True)) |
| 75 | async def index(request): |
| 76 | return web.json_response({"msg": "done", "data": {}}) |
| 77 | |
| 78 | |
| 79 | app = web.Application() |
| 80 | app.router.add_post("/v1/test", index) |
| 81 | |
| 82 | # init docs with all parameters, usual for ApiSpec |
| 83 | setup_aiohttp_apispec( |
| 84 | app=app, |
| 85 | title="My Documentation", |
| 86 | version="v1", |
| 87 | url="/api/docs/swagger.json", |
| 88 | swagger_path="/api/docs", |
| 89 | ) |
| 90 | |
| 91 | # Now we can find spec on 'http://localhost:8080/api/docs/swagger.json' |
| 92 | # and docs on 'http://localhost:8080/api/docs' |
| 93 | web.run_app(app) |
| 94 | ``` |
| 95 | Class based views are also supported: |
| 96 | ```python |
| 97 | class TheView(web.View): |
| 98 | @docs( |
| 99 | tags=["mytag"], |
| 100 | summary="View method summary", |
| 101 | description="View method description", |
| 102 | ) |
| 103 | @request_schema(RequestSchema(strict=True)) |
| 104 | @response_schema(ResponseSchema(), 200) |
| 105 | def delete(self): |
| 106 | return web.json_response( |
| 107 | {"msg": "done", "data": {"name": self.request["data"]["name"]}} |
| 108 | ) |
| 109 | |
| 110 | |
| 111 | app.router.add_view("/v1/view", TheView) |
| 112 | ``` |
| 113 | |
| 114 | As alternative you can add responses info to `docs` decorator, which is more compact way. |
| 115 | And it allows you not to use schemas for responses documentation: |
| 116 | |
| 117 | ```python |
| 118 | @docs( |
| 119 | tags=["mytag"], |
| 120 | summary="Test method summary", |
| 121 | description="Test method description", |
| 122 | responses={ |
| 123 | 200: { |
| 124 | "schema": ResponseSchema, |
| 125 | "description": "Success response", |
| 126 | }, # regular response |
| 127 | 404: {"description": "Not found"}, # responses without schema |
| 128 | 422: {"description": "Validation error"}, |
| 129 | }, |
| 130 | ) |
| 131 | @request_schema(RequestSchema(strict=True)) |
| 132 | async def index(request): |
| 133 | return web.json_response({"msg": "done", "data": {}}) |
| 134 | ``` |
| 135 | |
| 136 | ## Adding validation middleware |
| 137 | |
| 138 | ```Python |
| 139 | from aiohttp_apispec import validation_middleware |
| 140 | |
| 141 | ... |
| 142 | |
| 143 | app.middlewares.append(validation_middleware) |
| 144 | ``` |
| 145 | Now you can access all validated data in route from ```request['data']``` like so: |
| 146 | |
| 147 | ```Python |
| 148 | @docs( |
| 149 | tags=["mytag"], |
| 150 | summary="Test method summary", |
| 151 | description="Test method description", |
| 152 | ) |
| 153 | @request_schema(RequestSchema(strict=True)) |
| 154 | @response_schema(ResponseSchema, 200) |
| 155 | async def index(request): |
| 156 | uid = request["data"]["id"] |
| 157 | name = request["data"]["name"] |
| 158 | return web.json_response( |
| 159 | {"msg": "done", "data": {"info": f"name - {name}, id - {uid}"}} |
| 160 | ) |
| 161 | ``` |
| 162 | |
| 163 | |
| 164 | You can change ``Request``'s ``'data'`` param to another with ``request_data_name`` argument of |
| 165 | ``setup_aiohttp_apispec`` function: |
| 166 | |
| 167 | ```python |
| 168 | setup_aiohttp_apispec( |
| 169 | app=app, |
| 170 | request_data_name="validated_data", |
| 171 | ) |
| 172 | |
| 173 | ... |
| 174 | |
| 175 | |
| 176 | @request_schema(RequestSchema(strict=True)) |
| 177 | async def index(request): |
| 178 | uid = request["validated_data"]["id"] |
| 179 | ... |
| 180 | ``` |
| 181 | |
| 182 | Also you can do it for specific view using ```put_into``` |
| 183 | parameter (beginning from version 2.0): |
| 184 | |
| 185 | ```python |
| 186 | @request_schema(RequestSchema(strict=True), put_into="validated_data") |
| 187 | async def index(request): |
| 188 | uid = request["validated_data"]["id"] |
| 189 | ... |
| 190 | ``` |
| 191 | |
| 192 | ## More decorators |
| 193 | |
| 194 | Starting from version 2.0 you can use shortenings for documenting and validating |
| 195 | specific request parts like cookies, headers etc using those decorators: |
| 196 | |
| 197 | | Decorator name | Default put_into param | |
| 198 | |:----------|:-----------------| |
| 199 | | match_info_schema | match_info | |
| 200 | | querystring_schema | querystring | |
| 201 | | form_schema | form | |
| 202 | | json_schema | json | |
| 203 | | headers_schema | headers | |
| 204 | | cookies_schema | cookies | |
| 205 | |
| 206 | And example: |
| 207 | |
| 208 | ```python |
| 209 | @docs( |
| 210 | tags=["users"], |
| 211 | summary="Create new user", |
| 212 | description="Add new user to our toy database", |
| 213 | responses={ |
| 214 | 200: {"description": "Ok. User created", "schema": OkResponse}, |
| 215 | 401: {"description": "Unauthorized"}, |
| 216 | 422: {"description": "Validation error"}, |
| 217 | 500: {"description": "Server error"}, |
| 218 | }, |
| 219 | ) |
| 220 | @headers_schema(AuthHeaders) # <- schema for headers validation |
| 221 | @json_schema(UserMeta) # <- schema for json body validation |
| 222 | @querystring_schema(UserParams) # <- schema for querystring params validation |
| 223 | async def create_user(request: web.Request): |
| 224 | headers = request["headers"] # <- validated headers! |
| 225 | json_data = request["json"] # <- validated json! |
| 226 | query_params = request["querystring"] # <- validated querystring! |
| 227 | ... |
| 228 | ``` |
| 229 | |
| 230 | ## Custom error handling |
| 231 | |
| 232 | If you want to catch validation errors by yourself you |
| 233 | could use `error_callback` parameter and create your custom error handler. Note that |
| 234 | it can be one of coroutine or callable and it should |
| 235 | have interface exactly like in examples below: |
| 236 | |
| 237 | ```python |
| 238 | from marshmallow import ValidationError, Schema |
| 239 | from aiohttp import web |
| 240 | from typing import Optional, Mapping, NoReturn |
| 241 | |
| 242 | |
| 243 | def my_error_handler( |
| 244 | error: ValidationError, |
| 245 | req: web.Request, |
| 246 | schema: Schema, |
| 247 | error_status_code: Optional[int] = None, |
| 248 | error_headers: Optional[Mapping[str, str]] = None, |
| 249 | ) -> NoReturn: |
| 250 | raise web.HTTPBadRequest( |
| 251 | body=json.dumps(error.messages), |
| 252 | headers=error_headers, |
| 253 | content_type="application/json", |
| 254 | ) |
| 255 | |
| 256 | setup_aiohttp_apispec(app, error_callback=my_error_handler) |
| 257 | ``` |
| 258 | Also you can create your own exceptions and create |
| 259 | regular Request in middleware like so: |
| 260 | |
| 261 | ```python |
| 262 | class MyException(Exception): |
| 263 | def __init__(self, message): |
| 264 | self.message = message |
| 265 | |
| 266 | # It can be coroutine as well: |
| 267 | async def my_error_handler( |
| 268 | error, req, schema, error_status_code, error_headers |
| 269 | ): |
| 270 | await req.app["db"].do_smth() # So you can use some async stuff |
| 271 | raise MyException({"errors": error.messages, "text": "Oops"}) |
| 272 | |
| 273 | # This middleware will handle your own exceptions: |
| 274 | @web.middleware |
| 275 | async def intercept_error(request, handler): |
| 276 | try: |
| 277 | return await handler(request) |
| 278 | except MyException as e: |
| 279 | return web.json_response(e.message, status=400) |
| 280 | |
| 281 | |
| 282 | setup_aiohttp_apispec(app, error_callback=my_error_handler) |
| 283 | |
| 284 | # Do not forget to add your own middleware before validation_middleware |
| 285 | app.middlewares.extend([intercept_error, validation_middleware]) |
| 286 | ``` |
| 287 | |
| 288 | ## Build swagger web client |
| 289 | |
| 290 | #### 3.X SwaggerUI version |
| 291 | |
| 292 | Just add `swagger_path` parameter to `setup_aiohttp_apispec` function. |
| 293 | |
| 294 | For example: |
| 295 | |
| 296 | ```python |
| 297 | setup_aiohttp_apispec(app, swagger_path="/docs") |
| 298 | ``` |
| 299 | |
| 300 | Then go to `/docs` and see awesome SwaggerUI |
| 301 | |
| 302 | #### 2.X SwaggerUI version |
| 303 | |
| 304 | If you prefer older version you can use |
| 305 | [aiohttp_swagger](https://github.com/cr0hn/aiohttp-swagger) library. |
| 306 | `aiohttp-apispec` adds `swagger_dict` parameter to aiohttp web application |
| 307 | after initialization (with `setup_aiohttp_apispec` function). |
| 308 | So you can use it easily like: |
| 309 | |
| 310 | ```Python |
| 311 | from aiohttp_apispec import setup_aiohttp_apispec |
| 312 | from aiohttp_swagger import setup_swagger |
| 313 | |
| 314 | |
| 315 | def create_app(app): |
| 316 | setup_aiohttp_apispec(app) |
| 317 | |
| 318 | async def swagger(app): |
| 319 | setup_swagger( |
| 320 | app=app, swagger_url="/api/doc", swagger_info=app["swagger_dict"] |
| 321 | ) |
| 322 | |
| 323 | app.on_startup.append(swagger) |
| 324 | # now we can access swagger client on '/api/doc' url |
| 325 | ... |
| 326 | return app |
| 327 | ``` |
| 328 | |
| 329 | ## Versioning |
| 330 | |
| 331 | This software follows [Semantic Versioning](http://semver.org/). |
| 332 | |
| 333 | ------ |
| 334 | |
| 335 | Please star this repository if this project helped you! |