Skip to main content

API for Plain.

Project description

plain.api

Build APIs using class-based views.

The plain.api package provides lightweight view classes for building APIs using the same patterns as regular views. It also provides an APIKey model and support for generating OpenAPI documents.

# app/api/views.py
from plain.api.views import APIKeyView, APIView
from plain.http import JsonResponse
from plain.views.exeptions import ResponseException

from app.users.models import User
from app.pullrequests.models import PullRequest


class BaseAPIView(APIView, APIKeyView):
    def use_api_key(self, api_key):
        super().use_api_key()
        if user := self.api_key.users.first():
            self.request.user = user
        else:
            raise ResponseException(
                JsonResponse(
                    {"error": "API key not associated with a user."},
                    status_code=403,
                )
            )


class UserView(BaseAPIView):
    def get(self) -> User:
        return {
            "uuid": self.request.user.uuid,
            "username": self.request.user.username,
            "time_zone": str(self.request.user.time_zone),
        }


class PullRequestView(BaseAPIView):
    def get(self):
        try:
            pull = (
                PullRequest.objects.all()
                .visible_to_user(self.request.user)
                .get(uuid=self.url_kwargs["uuid"])
            )
        except PullRequest.DoesNotExist:
            return None

        return {
            "uuid": pull.uuid,
            "state": pull.state,
            "number": pull.number,
            "host_url": pull.host_url,
            "host_created_at": pull.host_created_at,
            "host_updated_at": pull.host_updated_at,
            "host_merged_at": pull.host_merged_at,
            "author": {
                "uuid": pull.author.uuid,
                "display_name": pull.author.display_name,
            },
        }
# app/api/urls.py
from plain.urls import Router, path

from . import views


class APIRouter(Router):
    namespace = "api"
    urls = [
        path("user/", views.UserView),
        path("pullrequests/<uuid:uuid>/", views.PullRequestView),
    ]

Authentication and authorization

TODO

Forms

TODO

API keys

The provided APIKey model includes randomly generated, unique API tokens that are automatically parsed by APIAuthViewMixin. The tokens can optionally be named and include an expires_at date.

Associating an APIKey with a user (or team, for example) is up to you. Most likely you will want to use a ForeignKey or a ManyToManyField.

# app/users/models.py
from plain import models
from plain.api.models import APIKey


@models.register_model
class User(models.Model):
    # other fields...
    api_key = models.ForeignKey(
        APIKey,
        on_delete=models.CASCADE,
        related_name="users",
        allow_null=True,
        required=False,
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["api_key"],
                condition=models.Q(api_key__isnull=False),
                name="unique_user_api_key",
            ),
        ]

Generating API keys is something you will need to do in your own code, wherever it makes sense to do so.

user = User.objects.first()
user.api_key = APIKey.objects.create(name="Example")
user.save()

If your API key is associated with something other than a user, or does not use the related name "users", you can define your own associate_api_key method.

OpenAPI

TODO

Project details


Download files

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

Source Distribution

plain_api-0.9.0.tar.gz (9.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

plain_api-0.9.0-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file plain_api-0.9.0.tar.gz.

File metadata

  • Download URL: plain_api-0.9.0.tar.gz
  • Upload date:
  • Size: 9.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.6.13

File hashes

Hashes for plain_api-0.9.0.tar.gz
Algorithm Hash digest
SHA256 d2c66dc492cc33eae8c59a98fde106129147c44bf7fa74e57477ae8af5e17f53
MD5 b52cb14d57f00b8699a6737e365a23ba
BLAKE2b-256 d7d42d24f73cdf70759900b1c08c6decab7bb4b918a49ff9335d40815c2044b2

See more details on using hashes here.

File details

Details for the file plain_api-0.9.0-py3-none-any.whl.

File metadata

  • Download URL: plain_api-0.9.0-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.6.13

File hashes

Hashes for plain_api-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0faf2a0c09d22c12035c6359a0607a196fc441cda76cd70beb58fc2b67668af9
MD5 203ced5b9591958626d424280b750345
BLAKE2b-256 696f52d3a8d0c684ec304890527c49428cc13ff8c77cbaa8a901e4f7556bcfa7

See more details on using hashes here.

Supported by

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