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:

type Toy {
  id: ID!
  name: String!
  price: Float!
  category: String!
  inStock: Boolean!
}

type Query {
  toys(category: String): [Toy!]!
  toy(id: ID!): Toy
}

type Mutation {
  createToy(name: String!, price: Float!, category: String!): Toy!
}

Explanation:

  • Types:

    • Toy: Represents a toy object with properties like id, name, price, category, and inStock.

    • 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):

query {
  toys
}

Response:

{
  "data": {
    "toys": [
      {
        "id": "1",
        "name": "Stuffed Bear",
        "price": 19.99,
        "category": "Plushies",
        "inStock": true
      },
      {
        "id": "2",
        "name": "Remote Control Car",
        "price": 49.99,
        "category": "Vehicles",
        "inStock": false
      }
    ]
  }
}

Query Example (Get a toy by ID):

query getToy($id: ID!) {
  toy(id: $id) {
    id
    name
    price
  }
}

Variables:

{
  "id": "1"
}

Response:

{
  "data": {
    "toy": {
      "id": "1",
      "name": "Stuffed Bear",
      "price": 19.99
    }
  }
}

Mutation Example (Create a new toy):

mutation createToy($name: String!, $price: Float!, $category: String!) {
  createToy(name: $name, price: $price, category: $category) {
    id
    name
    price
    category
  }
}

Variables:

{
  "name": "Building Blocks",
  "price": 24.99,
  "category": "Construction"
}

Response:

{
  "data": {
    "createToy": {
      "id": "3",  // Generated by the server
      "name": "Building Blocks",
      "price": 24.99,
      "category": "Construction"
    }
  }
}

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).

Last updated