← Back to Tutorials

28. GraphQL

pip install strawberry-graphql

Strawberry Setup

import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter

# Schema definition
@strawberry.type
class Item:
    id: int
    name: str
    price: float

@strawberry.type
class Query:
    @strawberry.field
    def items(self, skip: int = 0, limit: int = 10) -> List[Item]:
        return [Item(id=1, name="Sample", price=10.0)]

    @strawberry.field
    def item(self, id: int) -> Item:
        return Item(id=id, name="Item", price=20.0)

@strawberry.type
class Mutation:
    @strawberry.mutation
    def create_item(self, name: str, price: float) -> Item:
        return Item(id=2, name=name, price=price)

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

app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")

Test GraphQL

# Query at http://localhost:8000/graphql

{
  items(skip: 0, limit: 10) {
    id
    name
    price
  }
}

# Mutation
mutation {
  createItem(name: "New Item", price: 15.0) {
    id
    name
  }
}
✏️ Exercise: Create a GraphQL schema with User type (id, username, email). Add queries for users and user(id). Add a mutation to create a user.