chalice icon indicating copy to clipboard operation
chalice copied to clipboard

Swagger Integration

Open JamieCressey opened this issue 10 years ago • 10 comments

Swagger has been hugely beneficial when developing RESTful APIs, being able to generate Swagger specs from a Chalice app would be a massive time saving.

Docstring could then be used to define Swagger specific options per endpoint to define Swagger specific config such as path variable types etc.

JamieCressey avatar Jul 12 '16 19:07 JamieCressey

The console/API has a GetExport call that allows you to generate a service definition from an API. Given that we one of those routes in @app.route actually correspond to an API gateway resource, I think we could probably just rely on the default behavior from API gateway and expose something like chalice export or chalice api-export.

jamesls avatar Jul 12 '16 21:07 jamesls

That sounds like a reasonable starting point, and something pretty simple to implement as it. Would such a method provide the ability to include API and endpoint descriptions, parameter schemas etc though?

JamieCressey avatar Jul 13 '16 20:07 JamieCressey

if its helpful, here's what my export looked like (picked YAML for readability)

---
swagger: "2.0"
info:
  version: "2016-10-28T17:37:52Z"
  title: "helloworld"
host: "MYADDRESS.execute-api.us-east-1.amazonaws.com"
basePath: "/dev"
schemes:
- "https"
paths:
  /:
    get:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
        400:
          description: "400 response"
          schema:
            $ref: "#/definitions/Empty"
        500:
          description: "500 response"
          schema:
            $ref: "#/definitions/Empty"
        401:
          description: "401 response"
          schema:
            $ref: "#/definitions/Empty"
        403:
          description: "403 response"
          schema:
            $ref: "#/definitions/Empty"
        404:
          description: "404 response"
          schema:
            $ref: "#/definitions/Empty"
        429:
          description: "429 response"
          schema:
            $ref: "#/definitions/Empty"
        409:
          description: "409 response"
          schema:
            $ref: "#/definitions/Empty"
  /hook:
    post:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
        400:
          description: "400 response"
          schema:
            $ref: "#/definitions/Empty"
        500:
          description: "500 response"
          schema:
            $ref: "#/definitions/Empty"
        401:
          description: "401 response"
          schema:
            $ref: "#/definitions/Empty"
        403:
          description: "403 response"
          schema:
            $ref: "#/definitions/Empty"
        404:
          description: "404 response"
          schema:
            $ref: "#/definitions/Empty"
        429:
          description: "429 response"
          schema:
            $ref: "#/definitions/Empty"
        409:
          description: "409 response"
          schema:
            $ref: "#/definitions/Empty"
definitions:
  Empty:
    type: "object"
    title: "Empty Schema"

jonmcoe avatar Oct 28 '16 18:10 jonmcoe

I'm curious about the workflow for swagger. If you export the swagger file and add a bunch of documentation, do you have to manually merge the next time you change the API? Or, is there a way for comments from chalice to get included as API documentation?

lstroud avatar Jul 02 '17 20:07 lstroud

Ideally the route def's doc string would be extracted into the swagger, yes? It's available on foodef.__doc__. Some structure of the doc string might be imposed to match up descriptions of route parameters, such as the google or numpy conventions, eg: https://stackoverflow.com/questions/34331088/how-to-comment-parameters-for-pydoc

mnp avatar Jul 21 '17 15:07 mnp

I think that would work for documentation. However things like json schemas (Models) might be more challenging. We might have to merge the doc strings with another file.

lstroud avatar Aug 08 '17 17:08 lstroud

The chalice and swagger integration will be helpful for us.

There are some proposals about how can I implement it :

  1. There is py2swagger library, that use PLUGIN_SETTINGS variable to track all endpoints that should be in a swagger file. To use this library it needs to keep updated this config variable and add docstrings in each chalice endpoint for payload and responses. Problem: the full description in app.py for payload and response in each endpoint will make our code more complex and large. This will complicate readability and it should be added docstrings manually. There is a possibility to miss changes/fixes.
  2. Create chalice-swagger library that will use decorator for each endpoint to track the payload and responses for swagger file. The code in app.py will be look like:
from chalice_swagger import swagger_doc


@app.route("/example", methods=["POST"], authorizer=oauth)
@swagger_doc(schema=RequestPayloadSchema or None,
                          responses=[Response(status_code=400, title="Title", details={}, errors={}),
                           ...,
                          Response(status_code=200, title="Ok")])
def endpoint():
     pass

Problem: the full description in app.py for payload and response in each endpoint will make the code more complex and large. This will complicate readability. For each endpoint, it should be added payload schema or maybe use a dictionary to make it consistent with other endpoints.

  1. Generate swagger doc file while tests are running. Track the incoming payload and responses in conftest.py:create_event and collect them in some global variable SWAGGER_DICT. Create a separate library with:
  • a decorator that collect and process data (incoming payload and response)
  • pytest_sessionfinish for serialize SWAGGER_DICT to swagger.yaml file. The code will look like this:
# chalice-swagger lib

def swagger_info(swagger_info):
   def _decorator(func):
       def wrapp(*args, **kwargs):
           response = func()
           swagger_info["paths"][path][method] ...
           return response
       return wrapp
   return _decorator

def pytest_sessionfinish(session, exitstatus):
   if exitstatus == 0:
       with open("swagger.yml", "w+") as f:
           f.write(yaml.dump(SWAGGER_DICT))

# conftest.py

SWAGGER_DICT = {   "info": {},  "paths": {}}

@fixture
@swagger_info(SWAGGER_DICT)
def create_event():
    pass

Problem: In that case, it should be writing tests for each endpoint and each response that can be per endpoint (400, 404, 408, etc). And it can be not clear

  1. Create a library like flask-swagger that will be based on docstrings for the endpoint. Problem: it will increase the number of code lines in app.py in few times and developers should manually maintain it - I mean it won't be fully automatic.

The 3 option looks pretty nice because developer of chalice application shouldn't add anything manually. But I ain't sure that it's a good idea to generate docs while tests are running. Maybe one from these options will push you to a new idea or I can implement one from these. What do you think about it?

darlev91 avatar Aug 14 '19 11:08 darlev91

Could anyone find the best way to create the documentation for their chalice api ??, I was searching a lot on the internet and I did not find many options, this is the last I saw "https://github.com/jsfehler/leangle" but I still feel add lines of code to no avail. Hope to find something closer to just using typehint.

I appreciate if anyone shares their opinions.

dev-lusaja avatar Apr 13 '21 18:04 dev-lusaja

@dev-lusaja I used leangle and I did get the model schemas into my API. Since I didn't know how to add the validation in code, I used the aws console to set validation in body. This works as expected, the schema is used to validate requests. Now I am trying to find a way to do it in the cdk or chalice app, because every time I deploy the validation will be reset.

carolina-cascade avatar Apr 29 '21 13:04 carolina-cascade

Hello @carolina-cascade, I am not convinced of leangle (it seemed to me that it is a very invasive code), what I am looking for is that the documentation self-generates in the same style as fastAPI or perhaps something more similar to how springBoot handles the integration with swagger, for now opt to do a classic implementation (yml file) while I find a better way. Thank you very much for your comment, let's share how we are doing with our implementations.

dev-lusaja avatar Apr 29 '21 16:04 dev-lusaja