Giter Club home page Giter Club logo

Comments (5)

tomchristie avatar tomchristie commented on August 18, 2024

The latest release of the openapi-codec includes "summary", using the first line of the link description.

There's no particular plans to introduce "responses" at the moment, as it doesn't fit with Core API's simpler representation. For now we're leaving any documentation there to be expressed as part of the regular link documentation.

It'd be interesting to get an idea about where you're using this, and what your requirements for those attributes come from specifically? Is this in order to better interact with Swagger UI, or some other tool in particular?

from python-client.

GuillaumeCisco avatar GuillaumeCisco commented on August 18, 2024

Yes, I want to use Swagger UI.
Currently I use django swagger with django rest framework, and cannot correctly deal with Link from coreAPI (I override the schemas.SchemaGenerator).
I don't know how to set the summary for example.
https://github.com/core-api/python-client/blob/master/coreapi/document.py#L185

Just remarked django-swagger use openapi_codec 1.1.3. with no summary support.
https://github.com/core-api/python-openapi-codec/blob/1.1.3/openapi_codec/encode.py#L78
The last version 1.1.4 (today) includes it :
https://github.com/core-api/python-openapi-codec/blob/1.1.4/openapi_codec/encode.py#L78

from python-client.

tomchristie avatar tomchristie commented on August 18, 2024

Okay. There's a whole bunch of updates and fixes coming with 3.5, which may resolve the issues you're having. I'd suggest we close this off for now, and consider reopening if still required, once REST framework 3.5 lands. (Later this month)

from python-client.

GuillaumeCisco avatar GuillaumeCisco commented on August 18, 2024

Hell @tomchristie
Just tried the summary feature with the last version of django rest framework.
Works well

But still, it is impossible to add custom responses for displaying more informations about custom views.
The code related to responses is only:

def _get_responses(link):
    """
    Returns minimally acceptable responses object based
    on action / method type.
    """
    template = {'description': ''}
    if link.action.lower() == 'post':
        return {'201': template}
    if link.action.lower() == 'delete':
        return {'204': template}
    return {'200': template}

But a lot of things are available for responses:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responses-object

It will be very nice to add it.
Maybe the declaration can be made with yaml.

For example, for declaring parameters, I use a custom generator :

import yaml
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import response, schemas
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer

from django.conf.urls import url, include
from prototype.urls import router
from rest_framework.compat import coreapi, urlparse


class SchemaGenerator(schemas.SchemaGenerator):
    def get_link(self, path, method, view):
        """Custom the coreapi using the func.__doc__ .

        if __doc__ of the function exist, use the __doc__ building the coreapi. else use the default serializer.

        __doc__ in yaml format, eg:
        nota for type: Required.
        The type of the parameter. Since the parameter is not located at the request body,
        it is limited to simple types (that is, not an object).
        The value MUST be one of "string", "number", "integer", "boolean", "array" or "file".
        If type is "file", the consumes MUST be either "multipart/form-data", " application/x-www-form-urlencoded"
        or both and the parameter MUST be in "formData".

        ---

        desc: the desc of this api.
        ret: when success invoked, return xxxx
        err: when error occured, return xxxx
        input:
        - name: mobile
          desc: the mobile number
          type: string
          required: true
          location: form
        - name: promotion
          desc: the activity id
          type: integer
          required: true
          location: form
        """
        fields = self.get_path_fields(path, method, view)
        func = getattr(view, view.action) if getattr(view, 'action', None) else None
        _method_desc = ''
        if func and func.__doc__:
            a = func.__doc__.split('---')
            if len(a) == 2:
                try:
                    yaml_doc = yaml.load(a[1])
                except:
                    pass
                else:
                    if 'desc' in yaml_doc:
                        desc = yaml_doc.get('desc', '')
                        ret = yaml_doc.get('ret', '')
                        err = yaml_doc.get('err', '')
                        _method_desc = desc + '\n<br/>' + 'return: ' + ret + '<br/>' + 'error: ' + err
                        params = yaml_doc.get('input', [])
                        for i in params:
                            _name = i.get('name')
                            _desc = i.get('desc')
                            _required = i.get('required', True)
                            _type = i.get('type', 'string')
                            _location = i.get('location', 'form')
                            field = coreapi.Field(
                                name=_name,
                                location=_location,
                                required=_required,
                                description=_desc,
                                type=_type
                            )
                            fields.append(field)
            else:
                _method_desc = a[0]
                fields += self.get_serializer_fields(path, method, view)
        else:
            fields += self.get_serializer_fields(path, method, view)

        fields += self.get_pagination_fields(path, method, view)
        fields += self.get_filter_fields(path, method, view)

        if fields and any([field.location in ('form', 'body') for field in fields]):
            encoding = self.get_encoding(path, method, view)
        else:
            encoding = None

        if self.url and path.startswith('/'):
            path = path[1:]

        return coreapi.Link(
            url=urlparse.urljoin(self.url, path),
            action=method.lower(),
            encoding=encoding,
            fields=fields,
            description=_method_desc
        )


@api_view()
@renderer_classes([OpenAPIRenderer, SwaggerUIRenderer])
def schema_view(request):
    generator = SchemaGenerator(title='API', patterns=[url(r'^api/', include([
        url(r'^', include(router.urls))
    ])),])
    return response.Response(generator.get_schema(request=request))

I allows me to write description as:

'''
desc
'''

or

'''
desc
---
yaml desc
'''

In this last case, the desc is for developer and the yaml desc is for the documentation.

from python-client.

tomchristie avatar tomchristie commented on August 18, 2024

Noted.

from python-client.

Related Issues (20)

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.