Skip to content

Instantly share code, notes, and snippets.

@dtheodor
Last active June 8, 2016 09:21
Show Gist options
  • Save dtheodor/7a5ee33a1736bf9411d02a67ccd9457d to your computer and use it in GitHub Desktop.
Save dtheodor/7a5ee33a1736bf9411d02a67ccd9457d to your computer and use it in GitHub Desktop.

Goal

  1. Look into the RAML spec for Web APIs, and ways to visualize it (e.g. raml to html).

http://raml.org/ 2. Automatically generate a RAML spec for a basic web API built using django rest framework Serializers and APIViews

http://www.django-rest-framework.org/api-guide/serializers/

http://www.django-rest-framework.org/api-guide/views/ 3. (optional, may not have time) Also use the view's Serializers to deserialize request data and serialize response data

Design suggestion

Create a new base view class that, when inherited by classes that implement a concrete API view (e.g. the snippet view), allows to generate the RAML spec for that view:

from rest_framework.views import APIView
from rest_framework.serializers import Serializer

class RamlAPIView(APIView):
    """
    Inherit from this to allow specifying serializer attributes for each
    HTTP method that will result in RAML spec generation
    """
    
    @classmethod
    def generate_raml_spec(cls):
        # 1. use the cls.xxx_serializer attributes to figure out
        # available methods (GET, POST, etc.) and their corresponding
        # response/request serializers
        # 2. generate a RAML spec out of the serializer fields
    

class SnippetList(RamlAPIView):

    get_response_serializer = GetResponse
    post_request_serializer = PostRequest
    post_response_serializer = PostResponse
    
    def get(self, request):
        # ...
        
    def post(self, request):
        # ...

class GetResponse(Serializer):
     # a bunch of fields

class PostRequest(Serializer):
     # a bunch of fields
     
class PostResponse(Serializer):
     # a bunch of fields

Creating the SnippetList class as shown above should allow a RAML spec to be generated that should cover specifying request and response data for the GET and POST methods defined on the class

raml_spec = SnippetList.generate_raml_spec()
with open('snippet_list.spec') as f:
    f.write(raml_spec)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment