
[ad_1]
Handle CRUD operations with ease
The schema-first approach is nothing but we first define the schema for our GraphQL service and then we implement the code by matching the definitions in the defined schema.
we will use Ariadne
library for this.
Ariadne is a Python library for implementing GraphQL Server using schema-first approach. , Ariadne
We are going to build a GraphQL server that handles the CRUD operations of a book in a book store.
Simply, we will store the book information in our database. To simplify this project I haven’t used any kind of database, just used an in-memory store and focused more on the GraphQL part.
server operation
- add books
- get book by id
- List books by genre
- list all books
- update the book
- delete book
library setup
we are highly dependent on Ariadne
library, so we have to install it.
pip install ariadne
We need to make our GraphQL server an HTTP server that will receive HTTP requests, execute GraphQL queries, and return responses.
For this we use ASGI (asynchronous server gateway interface) like server Uvicorn,
pip install uvicorn
I invite you to define the schema and implement the code in your own way and requirement. Here we will see my way of defining the schema.
I have planned some GraphQL object types that can hold some information Books
in our book store
,
Here I have 2 object types and 1 enum type to describe a book.
Book
The type has the following fields:
title
— string type and nullbook_id
– ID Typegenre
– enum typeauthor
– series ofAuthor
type and non-nullable
Author
type:
- name – string type and non-nullable
- mail – string type
BookGenre
enum type:
- There are two values (
FICTION
,NONFICTION
,
The basic types to handle the above are Books
Information
Now we move on to define the entry point for our GraphQL service.
query type
I have above query type which has 3 fields.
book
– Get book details by providingbook_id
Logicallybooks
— Get a list of available booksgetbooks
– Get a list of books for the requested genre.getgenre
Argument is optional, its default value isFICTION
,
type GetBookResult{
isexists: Boolean!
book: Book
}
GetBookResult
The type has 2 fields:
isexists
– Boolean type and non-null, indicating whether book information is providedbook_id
- book
mutation type
The mutation type has 3 fields
add_book
– To create a book resource in our book store by providing input and response status of that request.update_book
— Updates existing book information and the response is the status of that request.delete_book
– Deletes the book with the given book ID and returns the status of the operation.
The above types are used in add_book
Mutation type field.
UpdateInput
And this PutStatus
used in type update_book
area of Mutation
type.
type DeleteStatus{
iserror: Boolean!
description: String
}
DeleteStatus
used in type delete_book
area of Mutation
type.
We have come to the end of our schema definition. Moving on to implementing the code.
in-memory store
As I mentioned earlier, I would use an in-memory data store (just a variable) to store the book information.
BOOK_STORE = [
{
"title": "Book 1", "book_id": 1, "genre": "FICTION",
"authors": [{"name": "Logesh", "mail": "logesh@domain.com"}]
},
]
Here I have initial mock data.
boilerplate code
We can load our schema in two ways:
- By defining our schema in a variable
- By defining our schema in a separate
.graphql
file
For example, in the first case:
from ariadne import QueryType, gql, make_executable_schema, MutationTypefrom ariadne.asgi import GraphQLtype_defs = gql("""
type Query {
book(book_id : ID!): GetBookResult
books: [Book]
}
""")query = QueryType()
mutation = MutationType()schema = make_executable_schema(type_defs, query, mutation)
app = GraphQL(schema, debug=True)
For the second case:
from ariadne import QueryType, make_executable_schema, MutationType, load_schema_from_pathfrom ariadne.asgi import GraphQLquery = QueryType()
mutation = MutationType()book_type_defs = load_schema_from_path("book_schema.graphql")
schema = make_executable_schema(book_type_defs, query, mutation)
app = GraphQL(schema, debug=True)
In the above code, we can see that I have loaded my schema from external file.
auxiliary work
I have written some helper functions like getting book information BOOK_STORE
,
The above function is used to get the book of the given ID BOOK_STORE
Variables (our database)
This function is used to check whether a book with the given ID exists or not.
This simple function is used to generate a unique ID, which is needed while creating a new book.
to remove the book from BOOK_STORE
variable by providing book id.
This function is used to get the list of books with the given genre.
solver
We are now ready to implement our GraphQL server resolver.
for book
field of query type we have above function to solve query and return dictionary with key(field) mentioned in our response type of this request in schema.
The above resolver function is used to resolve the query field – books
And getbooks
,
Now moving to mutation type.
The above function is used to create a new book in our Book
shop.
resolve_update_book
The function is used to update an existing book.
This function is used to delete the book by providing the book id.
Now we are done with our resolver, moving on to serve the customers.
by using uvicorn
We are going to serve our GraphQL server over HTTP.
Execute the below command to start the server.
uvicorn main:app
# uvicorn <filename>:<GraphQL object>
Uvicorn http://127.0.0.1:8000 . running on
question book

mutation add_book

question books

mutation update_book

question book

query gatebook

mutation delete_book

question book

We can also use Postman as a GraphQL client.
In this article, we saw how to build our own GraphQL Server in Python (Schema First Approach).
You can put this project in my . can find on Github, Thanks for reading.
[ad_2]
Source link
#Building #GraphQL #Server #schemafirst #approach #Python #Logesh #June