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