Example Using GraphQL
Toy Store API with GraphQL: A Hands-on Example
This example showcases a basic GraphQL API for a toy store, demonstrating the schema, queries, and mutations.
Schema:
Explanation:
Types:
Toy
: Represents a toy object with properties likeid
,name
,price
,category
, andinStock
.Query
: Defines available data retrieval operations.Mutation
: Defines data manipulation operations (optional, not all APIs have mutations).
Query:
toys(category: String)
: Retrieves a list of toys based on an optional category filter.toy(id: ID!)
: Fetches a specific toy by its ID.
Mutation:
createToy(name: String!, price: Float!, category: String!)
: Creates a new toy with provided details.
Query Example (Get all toys):
Response:
Query Example (Get a toy by ID):
Variables:
Response:
Mutation Example (Create a new toy):
Variables:
Response:
This example demonstrates the fundamental concepts of using a GraphQL API. By understanding the schema, you can craft queries to retrieve specific data and potentially use mutations to interact with the data (if supported).