Schema, types, queries, mutations, subscriptions, DataLoader
GraphQL API в Django проектах.
💡 Правило: Используйте GraphQL когда клиенту нужна гибкость в выборе данных.
# schema.py
import strawberry
from typing import List
@strawberry.type
class User:
id: strawberry.ID
username: str
email: str
@strawberry.type
class Query:
@strawberry.field
def user(self, id: strawberry.ID) -> User:
return User(id=id, username='john', email='john@example.com')
@strawberry.field
def users(self) -> List[User]:
return [User(id=1, username='john', email='john@example.com')]
@strawberry.type
class Mutation:
@strawberry.mutation
def create_user(self, username: str, email: str) -> User:
return User(id=1, username=username, email=email)
schema = strawberry.Schema(Query, Mutation)# urls.py
from strawberry.django.views import GraphQLView
from .schema import schema
urlpatterns = [
path('graphql/', csrf(GraphQLView.as_view(schema=schema, graphiql=True))),
]# Query
query {
user(id: "1") {
username
email
}
users {
username
}
}
# Mutation
mutation {
createUser(username: "john", email: "john@example.com") {
id
username
}
}Вопросы ещё не добавлены
Вопросы для этой подтемы ещё не добавлены.