microapi.views

class microapi.views.ApiView(**kwargs)

Just a bit of sugar on top of plain ol’ View.

Used as a base class for your API views to inherit from, & provides conveniences to make writing JSON APIs easier.

Usage:

from django.contrib.auth.decorators import login_required

from microapi import ApiView, ModelSerializer

from .models import BlogPost


# Inherit from the `ApiView` class...
class BlogPostView(ApiView):
    # ...then define `get`/`post`/`put`/`delete`/`patch` methods on the
    # subclass.

    # For example, we'll provide a list view on `get`.
    def get(self, request):
        posts = BlogPost.objects.all().order_by("-created")

        # The `render` method automatically creates a JSON response from
        # the provided data.
        return self.render({
            "success": True,
            "posts": self.serialize_many(posts),
        })

    # And handle creating a new blog post on `post`.
    @login_required
    def post(self, request):
        # Read the JSON
        data = self.read_json(request)

        # TODO: Validate the data here.

        serializer = ModelSerializer()
        post = serializer.from_dict(BlogPost(), data)
        post.save()

        return self.render({
            "success": True,
            "post": self.serialize(post),
        })
classmethod as_view(**initkwargs)

Main entry point for a request-response process.

bubble_exceptions = False

Control whether we handle exceptions or allow them to bubble up to Django.

dispatch(request, *args, **kwargs)

Light override to the built-in dispatch, to allow for automatic JSON serialization of errors (as opposed to HTML).

If you need the Django debug error, you can set the bubble_exceptions attribute on the class to True.

Parameters:
  • request (HttpRequest) – The provided request.

  • *args (list) – The unnamed view arguments from the URLconf.

  • **kwargs (dict) – The named view arguments from the URLconf.

Returns:

Typically, a JSON-encoded response.

Return type:

HttpResponse

http_method_names = ['get', 'post', 'put', 'patch', 'delete']

Control which HTTP methods are allowed to be responded to.

read_json(request, strict=True)

Reads the request body & returns the decoded JSON.

Parameters:
  • request (HttpRequest) – The received request

  • strict (bool) – (Optional) If provided, requires “correct” JSON headers to be present. Default is True.

Returns:

The decoded JSON body

Return type:

dict

render(data, status_code=200)

Creates a JSON response.

Parameters:
  • data (dict) – The data to return as JSON

  • status_code (int) – The desired HTTP status code. Default is http.OK (a.k.a. 200).

Returns:

The response for Django to provide to the user

Return type:

JsonResponse

render_error(msgs, status_code=500)

Creates an error JSON response.

Parameters:
  • msgs (list|str) – A list of message(s) to provide to the user. If a single string is provided, this will automatically get turned into a list.

  • status_code (int) – The desired HTTP status code. Default is http.APP_ERROR (a.k.a. 500).

Returns:

The error response for Django to provide to the user

Return type:

JsonResponse

serialize(obj)

A method for standardizing serialization.

A “rich” object (like a Model) is provided, & turned into a dict that is ready for JSON serialization.

By default, this provides some basic serialization for Django Model instances via ModelSerializer. You can extend this method to embelish the data, or override to perform your own custom serialization.

Parameters:

obj (Model) – The object to serialize.

Returns:

The data

Return type:

dict

serialize_many(objs)

Like serialize, but handles serialization for many objects.

Parameters:

objs (iterable) – An iterable of the objects to serialize.

Returns:

A list of serialized objects

Return type:

list

serializer = <microapi.serializers.ModelSerializer object>

What serializer we use by default.

validate(data)

A method for standardizing validation. Not automatically called anywhere.

Expected behavior is to return the validated data on success, or to call render_error with failures.

This MUST be implemented in the subclass by the user.

Parameters:

data (dict) – The data provided by the user.

Returns:

The validated data

Return type:

dict