Giter Club home page Giter Club logo

aiohttp_apiset's People

Contributors

aamalev avatar abogushov avatar dependabot[bot] avatar hh-h avatar pyup-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

aiohttp_apiset's Issues

Strict validation for query params

Couldn't find how to set strict validation for unnecessary query parameters.
I assume it is important opportunity to get exception when unexpected params (not defined in the swagger spec) was given

add support json source file/url

Hello,

I've tried use json specs to generate api, but example shows me empty page with methods. If i'll put url to swagger browser to json - it loaded api into the gui.

Openapi 3 not work with array

If you specify such a scheme

      parameters:
        - name: ids
          description: Some description
          required: false
          in: query
          style: form
          explode: false
          schema:
            type: array
            items:
              type: string
              format: uuid

Then an array of the following type comes to the backend
['3bd604c2-6edd-4a77-8233-6f93a05b593b,51e01ea8-9517-4288-b63a-90e265cb4e2c']

If you translate to the scheme of 3 versions, everything is fine

      parameters:
        - name: ids
          description: Some description
          required: false
          in: query
          type: array
          collectionFormat: csv
          items:
            type: string
            format: uuid

Version aiohtt_aipset = 0.9.13.2

Requests not validated with the "foreign specification" strategy

According to the documentation:
http://aiohttp-apiset.readthedocs.io/en/latest/
the library is supposed to work with a "foreign specification" strategy where the entire OpenAPI specification is read from an external file. So, when I initialize the SwaggerRouter like this:

router = SwaggerRouter("/path/to/openapi.spec.yaml")  # default_validate=True is implicit

I would suppose that the library should:

  1. provide a web-based documentation at apidoc/ URL, and
  2. provide an input/output validation of the requests and responses.

However, the library only performs the first point (i.e. makes the web-based documentation available). It does not validate requests or responses according to the provided OpenAPI specification. The relevant part of the code:

ds_swagger_op = get_docstring_swagger(handler)

is only able to utilize the OpenAPI specification for requests' validation and only when it is present in the request handler's docstring.

I believe that for this library to be useful with the "foreign specification" strategy, it needs to be able to validate the requests and responses using the OpenAPI specification which comes from an external file.

Moreover, it seems like the foreign specification strategy of this library is poorly documented, because the details of the actual behavior are left out and they need to be looked up manually from the code.

Improvements suggestions [RU]

Привет, накидали список того, что нас интересует (читай, что мы готовы сами добавить)

Пользуемся мы исключительно через документирование хендлеров, без yml схем

  1. Добавить новые типы в POST
    У нас есть несколько запросов без тела (text/plain) и мы заливаем csv (text/csv) файлы (например), а они не поддерживаются
    Решение: добавить новые кортежи для разных типов (.read, .post, .json)
    например
POSTS = (
'application/x-www-form-urlencoded',
'multipart/form-data',
'text/plain'
)
READS = (
'application/octet-stream',
'text/csv'
)
if request.content_type in POSTS:
  body = yield from requests.post()
  1. Скрыть роуты, которые добавляет apiset сам в [default]
GET /swagger/swagger.yaml
GET /swagger/
GET /swagger/{filename}

Решение: добавлять каким-нить кастомным роутом, который не попадет в аписет?

  1. Добавить возможность указать yml файл с definition'ами, при использовании через док стринги.
    Решение: новый флаг для конструктора, default = None, выдавать ошибку если задан path или просто игнорировать файл

Thoughts?

Unexpected value passed to handler when calling endpoint and not specifying the value for an array query parameter

Calling an endpoint and not specifying the value for an array query parameter results in handler receiving ['']

For example , when requesting curl -i -X GET "http://127.0.0.1:8080/test?ids=" in the handler, instead of [] I get ["]

Steps to reproduce
swagger.yaml

openapi: 2.0.0
info:
  version: 1.0
paths:
  /test:
    get:
      operationId: test_handler
      parameters:
        - name: ids
          required: false
          in: query
          type: array
          collectionFormat: csv
          items:
            type: string
            format: uuid
      responses:
        "200"

main.py

from typing import List

from aiohttp.web import Application, run_app
from aiohttp.web import Request, Response
from aiohttp_apiset import SwaggerRouter
from aiohttp_apiset.middlewares import jsonify
from aiohttp_apiset.swagger.operations import OperationIdMapping


async def test_handler(request: Request, ids: List[str]) -> Response:
    print(f"Received list: {ids}")

    return Response()


def main():
    router = SwaggerRouter(
        swagger_ui='/swagger/',
        search_dirs=['./'],
    )

    app = Application(router=router, middlewares=[jsonify])

    opmap = OperationIdMapping(test_handler=test_handler)

    router.include(spec='swagger.yaml', operationId_mapping=opmap)

    run_app(app)


if __name__ == "__main__":
    main()

Python version: 3.10.2
aiohttp_apiset vesion: 0.9.15

'parameters' key on a Path Item object is not supported

When using an OpenAPI v2 specification, which has the parameters key set on a Path Item object, this exception:

TypeError: pop() takes at most 1 argument (2 given)

is raised on this line:

handler = body.pop(self.HANDLER, None)

I think the problem is that the implementation assumes that the keys in the Path Item objects all hold the Operation Objects. However, the specification:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathItemObject
mentions that there can be a parameters key, which has a different type (a list). When encountered, it causes the mentioned exception to be raised.

allow to realy override basePath

Actually, SwaggerRouter.include accepts a basePath which is given to SwaggerRouter._include as override_basePath. But override_basePath do not override the existing basePath in the spec, instead it is use as a default value.

It would be great if override_basePath really overrides the basePath parameter defined inside the spec file.

My main use case is to use a (http://aiohttp.readthedocs.io/en/stable/whats_new_1_1.html#sub-applications)[sub application]. By this way the base path of sub application will be picked up from the spec file and override the basePath used for routes.

Note that the served swagger.yaml file should still contains the initial basePath parameter.

(great work, thx for sharing this project).

Allow using `operationId` to find the handler

I'd much rather have unique IDs in the existing operationId value for each handler, and then

  • either instantiate apiset with something like handlers_module='mymodule.handlers' to have it automatically getattr(mymodule.handlers, yaml['operationId']) the handlers from there.
  • or specify a dict in my app that maps operationIds to callables.

add support for collectionFormat

The swagger specification allows to define how arrays are formatted by specifying collectionFormat.
Actually, only the "multi" format is supported. It would be great to support other formats.

Support for nullable fields.

Swagger does not allow nullable fields for schemas like this:

DateInterval:
    type: object
    properties:
      from:
        type: string
        nullable: true
        format: date
        example: '2018-01-30'
      to:
        type: string
        nullable: true
        format: date
        example: '2018-01-30'

But if I remove nullable: true json-schema validation cannot be passed.

OpenAPI 3.0.0: basePath does not appear to be resolved correctly

Hello,

Using aiohttp_apiset together with a yaml-based specs file with openapi: "3.0.0", my code looks like this:

    opmap = create_default_operation_mapping(Path(BASE / SPEC_FILE))

    router = SwaggerRouter(
        swagger_ui='/apidoc/',
        version_ui=3,
        search_dirs=[BASE],
        default_validate=True,
    )
   app = web.Application(
        router=router,
        middlewares=[jsonify],
    )
    router.set_cors(app, domains='*', headers=(
        (hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, hdrs.AUTHORIZATION),
    ))
    router.include(
        spec='director_api.yaml',
        operationId_mapping=opmap,
        name='v1',  # name to access in swagger-ui,
        basePath="/v1" # THIS FIXES THE ISSUE BUT IS NOT SO NICE
    )

my specs file looks like this (just exposing the the server url part):

openapi: "3.0.0"
...
servers:
  - url: localhost:{port}/{basePath}
    description: Development server
    variables:
      port: 
        default: '8001'
      basePath:
        default: v1

the call to router.include when done without using the argument basePath does not serve the REST API on /v1 like it used to do with v2 of the specs. I think this is due to the fact that basePath parameter does not exist in OAS3.

Best regards,
Sylvain

How to contact with you?

Hey, we use your library in production, so I want to say thank you first :)
I have a few ideas how to improve the library, but I want to discuss it first. How can I contact with you? email, vk, telegram.

python 3.10 is not supported

when trying to switch to python 3.10, the import breaks

#16 91.90     from aiohttp_apiset.swagger.operations import OperationIdMapping
#16 91.90 /usr/local/lib/python3.10/site-packages/aiohttp_apiset/__init__.py:1: in <module>
#16 91.90     from .swagger.router import SwaggerRouter
#16 91.90 /usr/local/lib/python3.10/site-packages/aiohttp_apiset/swagger/router.py:2: in <module>
#16 91.90     from collections import Mapping
#16 91.90 E   ImportError: cannot import name 'Mapping' from 'collections' (/usr/local/lib/python3.10/collections/__init__.py)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.