@@ -20,17 +20,29 @@ class Book:
2020 author : str
2121
2222
23- def get_books ():
24- return [Book (title = 'The Great Gatsby' , author = 'F. Scott Fitzgerald' , )]
23+ my_books = [
24+ Book (title = "The Great Gatsby" , author = "F. Scott Fitzgerald" )
25+ ]
2526
2627
2728@strawberry .type
2829class Query :
29- books : List [Book ] = strawberry .field (resolver = get_books )
30+ @strawberry .field
31+ def get_books (self ) -> List [Book ]:
32+ return my_books
33+
34+
35+ @strawberry .type
36+ class Mutation :
37+ @strawberry .mutation
38+ def add_book (self , title : str , author : str ) -> Book :
39+ book = Book (title = title , author = author )
40+ my_books .append (book )
41+ return book
3042
3143
3244# this line creates the strawberry schema
33- my_book_schema = strawberry .Schema (query = Query )
45+ my_book_schema = strawberry .Schema (query = Query , mutation = Mutation )
3446
3547
3648# now this is the important part
@@ -67,6 +79,34 @@ def cache_key(self) -> str:
6779
6880client = Client (StrawberryBackend (my_book_schema ))
6981
70- response : GraphQLResponse = client .query .books (_fields = ["title" , "author" ])
82+ # note that the operation is now named "getBooks"
83+ # instead of the actual method "get_books"
84+ # This is due to the automatic camel case conversation in strawberry
85+ # https://strawberry.rocks/docs/types/schema-configurations
86+ response : GraphQLResponse = client .query .getBooks (_fields = ["title" , "author" ])
87+
88+ print (response .data ) # {"getBooks": [{"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}]}
89+
90+ response : GraphQLResponse = client .mutation .addBook (
91+ title = "1984" ,
92+ author = "George Orwell" ,
93+ _fields = ["title" , "author" ]
94+ )
7195
72- print (response .data ) # {'books': [{'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald'}]}
96+ print (response .data )
97+ # {
98+ # "addBook": {
99+ # "title": "1984",
100+ # "author": "George Orwell"
101+ # }
102+ # }
103+
104+ response : GraphQLResponse = client .query .getBooks (_fields = ["title" , "author" ])
105+
106+ print (response .data )
107+ # {
108+ # "getBooks": [
109+ # {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"},
110+ # {"title": "1984", "author": "George Orwell"}
111+ # ]
112+ # }
0 commit comments