Skip to main content

Implement a JSON API using dataclasses

Project description

This library provides a decorator that when applied to a Django views does JSON serialization and enforces schemas using the dataclasses-jsonschema library.

It also enables you to export your API definition to an OpenAPI spec file. This enables you to autogenerate client libraries.

Usage

To use it, decorate your view functions with the appropriate HTTP method provided by django-dataclasses (post, get, patch, or put). Annotate the return values of your functions with the appropriate dataclass type. Views that take input require an additional body parameter with the appropriate dataclass type annotation:

from django import http
import django_dataclasses


@django_dataclasses.dataclass
class StringLengthRequest:
    input: str


@django_dataclasses.dataclass
class StringLengthResponse:
    length: int


@django_dataclasses.login_required
@django_dataclasses.post
def string_length(request: http.HttpRequest, body: StringLengthRequest) -> StringLengthResponse:
    """Calculate the length of a string"""
    return StringLengthResponse(length=len(body.input))

Schema export

This library was inspired by the convenience of using autogenerated gRPC client libraries. Not everyone can adopt gRPC, and django-dataclasses aims to provides a similar toolkit for JSON APIs.

Export your schemas in the OpenAPI format using this management command. You need to add django_dataclasses to your INSTALLED_APPS for it to be available:

./manage.py openapi_export > api.json

Then, use another library to autogenerate client libraries. For example, you can use openapi-typescript-codegen to generate a JavaScript client complete with typed methods by running:

yarn add --dev openapi-typescript-codegen
yarn run openapi --input api.json --output api/

Raising Errors in Views

To return an error response in your views, simply raise django_dataclasses.ErrorResponse. For example, in this instance we raise an ErrorResponse if the login credentials are invalid:

if user is not None:
    login(request, user)
    return UserResponse(user.username)
else:
    raise django_dataclasses.ErrorResponse("Incorrect username or password", 401)

The exception will be caught by the django_dataclasses.<request-method> decorator and an appropriate HTTP response will be returned.

License

Contributions are made under the terms of the Apache License, Version 2.0. See LICENSE.

Contributing

This project uses pyenv, please install it first. When running on a Mac, the Makefile uses Homebrew to install dependencies. On other platforms please install them manually.

Clone the repo and setup your development environment by running:

git clone https://gitlab.com/roivant/oss/django-dataclasses.git
make setup

Run the tests and code validations:

make test
make validate

You can test exporting the openapi schema and compiling it to JavaScript using openapi-typescript-codegen by running this command. The output files are put in a folder api/:

make api

Contributors must adhere to the Contributor Covenant Code of Conduct. Please report suspected violations to vant.tech.eng@roivant.com.

About the template

This repository was created from the temple-python template. If you have access to that repository, apply updates from the template by running:

temple update

What tools are included?

  • A Makefile for convenience; use make setup to setup your dev environment

  • A build configuration in .gitlab-ci.yml

  • A test framework using pytest and requiring 100% coverage; use make test to run

  • Python auto-formatting using black, flake8, and isort via a git pre-commit hook

  • Automatic versioning and ChangeLog using PBR

Versioning using PBR

The PBR library will automatically increment the version when you commit to the main branch by merging your pull request. The commit message that you enter on GitHub when merging will determine what version number is assigned, using Semantic Versioning.

  • Messages starting with Sem-Ver: bugfix, or with no matching message will bump the PATCH number

  • Messages starting with Sem-Ver: feature, or Sem-Ver: deprecation, will bump the MINOR number.

  • Messages starting with Sem-Ver: api-break, will bump the MAJOR number.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

django_dataclasses-0.1.8-py3-none-any.whl (17.4 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page