← Back to Python

All Topics

Advertisement

Learn/Python/GraphQL

GraphQL with Python - Graphene, Strawberry, Schemas

Topic: GraphQL with Python

Advertisement

Introduction

GraphQL provides a flexible alternative to REST APIs. Python offers several GraphQL libraries including Graphene and Strawberry that make implementing GraphQL servers straightforward.

Graphene Implementation

# schema.py
import graphene
from graphene import ObjectType, String, Int, List, Field
from datetime import datetime

class Author(ObjectType):
    id = Int()
    name = String()
    email = String()
    books = List(lambda: Book)

class Book(ObjectType):
    id = Int()
    title = String()
    published_year = Int()
    author = Field(Author)

class Query(ObjectType):
    all_books = List(Book)
    book = Field(Book, id=Int())
    all_authors = List(Author)
    
    def resolve_all_books(self, info):
        return Book.objects.all()
    
    def resolve_book(self, info, id):
        return Book.objects.get(id=id)
    
    def resolve_all_authors(self, info):
        return Author.objects.all()

class CreateBook(graphene.Mutation):
    class Arguments:
        title = String(required=True)
        published_year = Int()
        author_id = Int(required=True)
    
    book = Field(Book)
    
    def mutate(self, info, title, author_id, published_year=None):
        book = Book.objects.create(
            title=title,
            author_id=author_id,
            published_year=published_year
        )
        return CreateBook(book=book)

class Mutation(ObjectType):
    create_book = CreateBook.Field()

schema = graphene.Schema(query=Query, mutation=Mutation)

Strawberry Implementation

# schema.py
import strawberry
from typing import List, Optional
from datetime import datetime

@strawberry.type
class Author:
    id: int
    name: str
    email: str
    
    @strawberry.field
    def books(self) -> List['Book']:
        return Book.objects.filter(author_id=self.id)

@strawberry.type
class Book:
    id: int
    title: str
    published_year: Optional[int]
    author: Author

@strawberry.input
class BookInput:
    title: str
    published_year: Optional[int] = None
    author_id: int

@strawberry.type
class Query:
    @strawberry.field
    def books(self) -> List[Book]:
        return Book.objects.all()
    
    @strawberry.field
    def book(self, id: int) -> Optional[Book]:
        return Book.objects.get(id=id)
    
    @strawberry.field
    def authors(self) -> List[Author]:
        return Author.objects.all()

@strawberry.type
class Mutation:
    @strawberry.mutation
    def create_book(self, input: BookInput) -> Book:
        book = Book.objects.create(
            title=input.title,
            author_id=input.author_id,
            published_year=input.published_year
        )
        return book

schema = strawberry.Schema(query=Query, mutation=Mutation)

FastAPI Integration

from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter

app = FastAPI()

graphql_router = GraphQLRouter(schema)

app.include_router(graphql_router, prefix="/graphql")

Practice Problems

  1. Create a GraphQL schema for a blogging platform with posts and comments
  2. Implement pagination in GraphQL queries
  3. Add authentication to GraphQL resolvers
  4. Create mutations for updating and deleting records
  5. Implement subscriptions for real-time updates

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →