Pytigon integrates GraphQL through Django's ObjectType system, giving clients the ability to request exactly the data they need. No more, no less. No over-fetching, no under-fetching.
GraphQL complements Pytigon's REST-like views. Use REST for standard CRUD operations and GraphQL when:
GraphQL types map to your Django models:
import graphene
from graphene_django import DjangoObjectType
from .models import Album, Track
class AlbumType(DjangoObjectType):
class Meta:
model = Album
fields = ("id", "name", "artist", "release_date", "tracks")
class TrackType(DjangoObjectType):
class Meta:
model = Track
fields = ("id", "title", "duration", "album")
Define queries that expose your data:
class Query(graphene.ObjectType):
all_albums = graphene.List(AlbumType)
album = graphene.Field(AlbumType, id=graphene.Int())
def resolve_all_albums(self, info, **kwargs):
return Album.objects.all()
def resolve_album(self, info, id):
return Album.objects.get(pk=id)
Define mutations for creating and updating data:
class CreateAlbum(graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
artist = graphene.String(required=True)
album = graphene.Field(AlbumType)
def mutate(self, info, name, artist):
album = Album(name=name, artist=artist)
album.save()
return CreateAlbum(album=album)
Pytigon's GraphQL integration respects the same authentication and permission system as the rest of the application:
from pytigon_lib.schdjangoext.graphql import login_required
class Query(graphene.ObjectType):
all_albums = graphene.List(AlbumType)
@login_required
def resolve_all_albums(self, info, **kwargs):
return Album.objects.all()
The GraphQL endpoint is available at /graphql/. Use any GraphQL client to query it:
query {
allAlbums {
name
artist
tracks {
title
duration
}
}
}
Pytigon provides OAuth support for GraphQL endpoints, enabling third-party applications to authenticate and access data through GraphQL with token-based authorization.