GraphQL API

MyAppAPI offers a powerful GraphQL API that provides a flexible and efficient way to interact with our platform. With GraphQL, you can request exactly the data you need, combine multiple resources in a single request, and take advantage of a strongly-typed schema.

Overview

GraphQL is a query language for APIs that enables clients to request exactly the data they need. Unlike our REST API, which uses multiple endpoints for different resources, our GraphQL API exposes a single endpoint:

https://api.myappapi.com/graphql

Key Benefits

Precise Data Fetching

Precise Data Fetching

Request only the data you need, reducing bandwidth usage and improving performance.

Reduced Network Requests

Reduced Network Requests

Combine multiple resources in a single request to minimize network round trips.

Strongly Typed Schema

Strongly Typed Schema

Discover available data and operations through introspection, enabling better tooling and development experience.

API Evolution

API Evolution

Add new fields and types without versioning or breaking existing queries.

Note: Our GraphQL API complements rather than replaces our REST API. You can use whichever best fits your use case, or even combine both approaches.

Getting Started

To get started with our GraphQL API, you'll need:

  1. An API key or authentication token (see Authentication)
  2. A GraphQL client or HTTP client capable of making POST requests

Your First Query

Here's a simple query to retrieve your user information:

{
  me {
    id
    name
    email
    createdAt
  }
}
curl -X POST 'https://api.myappapi.com/graphql' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -d '{
    "query": "{ me { id name email createdAt } }"
  }'
// Using fetch
const fetchUserData = async () => {
  const response = await fetch('https://api.myappapi.com/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify({
      query: `{
        me {
          id
          name
          email
          createdAt
        }
      }`
    })
  });
  
  const { data } = await response.json();
  console.log(data);
};

fetchUserData();
import requests

url = 'https://api.myappapi.com/graphql'
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
}

query = """
{
  me {
    id
    name
    email
    createdAt
  }
}
"""

response = requests.post(url, json={'query': query}, headers=headers)
data = response.json()
print(data)

Response:

{
  "data": {
    "me": {
      "id": "usr_123456789",
      "name": "John Doe",
      "email": "[email protected]",
      "createdAt": "2025-01-15T08:30:00Z"
    }
  }
}

Schema

Our GraphQL schema defines the data types, queries, mutations, and subscriptions available in our API. You can explore the full schema using tools like GraphiQL or Apollo Studio.

Core Types

Here are some of the key types in our schema:

type User {
  id: ID!
  name: String!
  email: String!
  role: UserRole!
  resources: [Resource!]!
  webhooks: [Webhook!]!
  createdAt: DateTime!
  updatedAt: DateTime!
}

enum UserRole {
  ADMIN
  USER
  VIEWER
}

type Resource {
  id: ID!
  name: String!
  description: String
  owner: User!
  status: ResourceStatus!
  data: JSONObject
  createdAt: DateTime!
  updatedAt: DateTime!
}

enum ResourceStatus {
  ACTIVE
  ARCHIVED
  PENDING
}

type Webhook {
  id: ID!
  url: String!
  events: [WebhookEvent!]!
  user: User!
  createdAt: DateTime!
  updatedAt: DateTime!
}

enum WebhookEvent {
  RESOURCE_CREATED
  RESOURCE_UPDATED
  RESOURCE_DELETED
  USER_CREATED
  USER_UPDATED
}

type Event {
  id: ID!
  type: String!
  resourceId: ID
  data: JSONObject!
  createdAt: DateTime!
}

scalar DateTime
scalar JSONObject

Schema Introspection

GraphQL provides built-in introspection capabilities to explore and discover the schema. You can query the schema itself to understand available types, fields, and operations.

{
  __schema {
    types {
      name
      kind
      description
    }
  }
}

Queries

GraphQL queries allow you to retrieve data from our API. Our schema provides various root query fields to access different resources.

Available Queries

Query Description Arguments
me Get the currently authenticated user None
user(id: ID!) Get a user by ID id: The ID of the user
users(filter: UserFilter, pagination: PaginationInput) Get a list of users filter: Filter criteria for users
pagination: Pagination options
resource(id: ID!) Get a resource by ID id: The ID of the resource
resources(filter: ResourceFilter, pagination: PaginationInput) Get a list of resources filter: Filter criteria for resources
pagination: Pagination options
webhook(id: ID!) Get a webhook by ID id: The ID of the webhook
webhooks(pagination: PaginationInput) Get a list of webhooks pagination: Pagination options
event(id: ID!) Get an event by ID id: The ID of the event
events(filter: EventFilter, pagination: PaginationInput) Get a list of events filter: Filter criteria for events
pagination: Pagination options

Query Example: Fetching Resources with Their Owners

{
  resources(
    filter: { status: ACTIVE }
    pagination: { limit: 5, offset: 0 }
  ) {
    pageInfo {
      totalCount
      hasNextPage
    }
    edges {
      node {
        id
        name
        description
        status
        owner {
          id
          name
          email
        }
        createdAt
      }
    }
  }
}

Response:

{
  "data": {
    "resources": {
      "pageInfo": {
        "totalCount": 42,
        "hasNextPage": true
      },
      "edges": [
        {
          "node": {
            "id": "res_123456789",
            "name": "Project Alpha",
            "description": "A sample project",
            "status": "ACTIVE",
            "owner": {
              "id": "usr_123456789",
              "name": "John Doe",
              "email": "[email protected]"
            },
            "createdAt": "2025-01-15T08:30:00Z"
          }
        },
        {
          "node": {
            "id": "res_987654321",
            "name": "Project Beta",
            "description": "Another sample project",
            "status": "ACTIVE",
            "owner": {
              "id": "usr_987654321",
              "name": "Jane Smith",
              "email": "[email protected]"
            },
            "createdAt": "2025-01-10T14:20:00Z"
          }
        },
        // ... more resources
      ]
    }
  }
}

Mutations

Mutations allow you to modify data in our API. Unlike queries, which only retrieve data, mutations can create, update, or delete resources.

Available Mutations

Mutation Description Arguments
createUser(input: CreateUserInput!) Create a new user input: User creation data
updateUser(id: ID!, input: UpdateUserInput!) Update an existing user id: The ID of the user to update
input: User update data
deleteUser(id: ID!) Delete a user id: The ID of the user to delete
createResource(input: CreateResourceInput!) Create a new resource input: Resource creation data
updateResource(id: ID!, input: UpdateResourceInput!) Update an existing resource id: The ID of the resource to update
input: Resource update data
deleteResource(id: ID!) Delete a resource id: The ID of the resource to delete
createWebhook(input: CreateWebhookInput!) Create a new webhook input: Webhook creation data
updateWebhook(id: ID!, input: UpdateWebhookInput!) Update an existing webhook id: The ID of the webhook to update
input: Webhook update data
deleteWebhook(id: ID!) Delete a webhook id: The ID of the webhook to delete

Mutation Example: Creating a Resource

mutation {
  createResource(input: {
    name: "New Project",
    description: "A brand new project",
    status: ACTIVE,
    data: {
      category: "Development",
      priority: "High"
    }
  }) {
    resource {
      id
      name
      description
      status
      createdAt
    }
  }
}

Response:

{
  "data": {
    "createResource": {
      "resource": {
        "id": "res_567890123",
        "name": "New Project",
        "description": "A brand new project",
        "status": "ACTIVE",
        "createdAt": "2025-05-11T14:30:00Z"
      }
    }
  }
}

Input Types

Our mutations use input types to specify the data for creating or updating resources. Here are some key input types:

input CreateUserInput {
  name: String!
  email: String!
  role: UserRole
}

input UpdateUserInput {
  name: String
  email: String
  role: UserRole
}

input CreateResourceInput {
  name: String!
  description: String
  status: ResourceStatus
  data: JSONObject
}

input UpdateResourceInput {
  name: String
  description: String
  status: ResourceStatus
  data: JSONObject
}

input CreateWebhookInput {
  url: String!
  events: [WebhookEvent!]!
}

input UpdateWebhookInput {
  url: String
  events: [WebhookEvent!]
}

input PaginationInput {
  limit: Int = 10
  offset: Int = 0
}

Subscriptions

Subscriptions enable real-time updates through a persistent connection. When subscribing to specific events, you'll receive updates whenever those events occur.

Note: Subscriptions require a WebSocket connection, unlike queries and mutations which use HTTP.

Available Subscriptions

Subscription Description Arguments
resourceUpdated(id: ID!) Subscribe to updates for a specific resource id: The ID of the resource to monitor
userUpdated(id: ID!) Subscribe to updates for a specific user id: The ID of the user to monitor
eventCreated(types: [String!]) Subscribe to new events of specific types types: List of event types to monitor

Subscription Example: Monitoring Resource Updates

subscription {
  resourceUpdated(id: "res_123456789") {
    id
    name
    status
    updatedAt
  }
}

When the resource is updated, you'll receive a message like:

{
  "data": {
    "resourceUpdated": {
      "id": "res_123456789",
      "name": "Project Alpha Updated",
      "status": "ACTIVE",
      "updatedAt": "2025-05-11T15:45:00Z"
    }
  }
}

Client Implementation

To implement subscriptions in your client, you'll need a GraphQL client that supports WebSocket connections. Popular choices include:

Authentication

Authentication for our GraphQL API works the same way as our REST API. You can use API keys, OAuth tokens, or JWT tokens, depending on your use case.

HTTP Header Authentication

Include your authentication token in the HTTP Authorization header:

Authorization: Bearer YOUR_API_KEY

WebSocket Authentication (for Subscriptions)

For WebSocket connections, you can include your authentication token as a query parameter in the connection URL:

wss://api.myappapi.com/graphql?token=YOUR_API_KEY

Alternatively, you can pass the token during the WebSocket handshake using the connection_init message:

{
  "type": "connection_init",
  "payload": {
    "Authorization": "Bearer YOUR_API_KEY"
  }
}

For more details on authentication methods, refer to our Authentication Guide.

Error Handling

GraphQL errors are returned in a standardized format, making it easier to handle them in your client applications.

Error Structure

GraphQL responses may include an "errors" array alongside the "data" field:

{
  "data": {
    "user": null
  },
  "errors": [
    {
      "message": "User not found",
      "path": ["user"],
      "extensions": {
        "code": "NOT_FOUND",
        "details": {
          "userId": "usr_nonexistent"
        }
      }
    }
  ]
}

Error Codes

Code Description
UNAUTHENTICATED Not authenticated or invalid authentication credentials
FORBIDDEN Authenticated but not authorized to perform the requested operation
BAD_USER_INPUT Invalid input provided in the request
NOT_FOUND Requested resource not found
ALREADY_EXISTS Resource already exists (e.g., when creating a resource with a duplicate identifier)
RATE_LIMITED Rate limit exceeded
INTERNAL_SERVER_ERROR Internal server error occurred

For more details on handling errors, refer to our Error Handling Guide.

Pagination

Our GraphQL API uses the Relay-style cursor pagination pattern for lists of objects, making it easier to paginate through large result sets.

Pagination Structure

Lists are returned with a connection structure that includes:

  • pageInfo: Information about the pagination state
  • edges: The actual items, each wrapped in an "edge" object
type ResourceConnection {
  pageInfo: PageInfo!
  edges: [ResourceEdge!]!
}

type ResourceEdge {
  node: Resource!
  cursor: String!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
  totalCount: Int!
}

Pagination Example

{
  resources(first: 10, after: "cursor_abc123") {
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
      totalCount
    }
    edges {
      cursor
      node {
        id
        name
        status
      }
    }
  }
}

Response:

{
  "data": {
    "resources": {
      "pageInfo": {
        "hasNextPage": true,
        "hasPreviousPage": true,
        "startCursor": "cursor_def456",
        "endCursor": "cursor_ghi789",
        "totalCount": 42
      },
      "edges": [
        {
          "cursor": "cursor_def456",
          "node": {
            "id": "res_123456789",
            "name": "Project Alpha",
            "status": "ACTIVE"
          }
        },
        // ... more resources
        {
          "cursor": "cursor_ghi789",
          "node": {
            "id": "res_987654321",
            "name": "Project Beta",
            "status": "ACTIVE"
          }
        }
      ]
    }
  }
}

Pagination Parameters

You can use the following parameters for pagination:

  • first: Number of items to return (forward pagination)
  • after: Cursor to start after (forward pagination)
  • last: Number of items to return (backward pagination)
  • before: Cursor to end before (backward pagination)

For more information on pagination, see our Pagination Guide.

Tooling

There are many tools available to help you work with our GraphQL API more effectively.

GraphQL IDEs

  • GraphiQL: A browser-based IDE for exploring GraphQL APIs
  • GraphQL Playground: An alternative GraphQL IDE with more features
  • Apollo Studio: A powerful platform for developing and monitoring GraphQL APIs

GraphQL Clients

  • Apollo Client: A comprehensive GraphQL client for JavaScript
  • Relay: Facebook's GraphQL client for React applications
  • graphql-request: A minimal GraphQL client for simple use cases
  • gql: A Python client for GraphQL

Code Generation

You can generate type-safe code for your API clients using tools like:

Examples

Here are some practical examples to help you get started with our GraphQL API.

Fetching Multiple Resources in a Single Request

{
  # Get current user information
  me {
    id
    name
    email
  }
  
  # Get active resources
  activeResources: resources(filter: { status: ACTIVE }, pagination: { limit: 5 }) {
    edges {
      node {
        id
        name
        status
      }
    }
  }
  
  # Get recent events
  recentEvents: events(pagination: { limit: 5 }) {
    edges {
      node {
        id
        type
        createdAt
      }
    }
  }
}

Creating a Resource and Registering a Webhook

mutation {
  # Create a new resource
  newResource: createResource(input: {
    name: "New Project",
    description: "A brand new project",
    status: ACTIVE
  }) {
    resource {
      id
      name
    }
  }
  
  # Register a webhook to monitor updates to the resource
  newWebhook: createWebhook(input: {
    url: "https://example.com/webhooks/myappapi",
    events: [RESOURCE_UPDATED, RESOURCE_DELETED]
  }) {
    webhook {
      id
      url
      events
    }
  }
}

Complex Query with Filtering and Relationships

{
  # Get resources created in the last 7 days
  recentResources: resources(
    filter: {
      createdAfter: "2025-05-04T00:00:00Z"
    },
    pagination: { limit: 10 }
  ) {
    pageInfo {
      totalCount
      hasNextPage
      endCursor
    }
    edges {
      node {
        id
        name
        status
        
        # Include the owner details
        owner {
          id
          name
          email
        }
        
        # Include recent events for this resource
        events(pagination: { limit: 3 }) {
          edges {
            node {
              id
              type
              data
              createdAt
            }
          }
        }
        
        createdAt
        updatedAt
      }
    }
  }
}

Real-time Events with Subscriptions

subscription {
  # Subscribe to resource creation and update events
  eventCreated(types: ["RESOURCE_CREATED", "RESOURCE_UPDATED"]) {
    id
    type
    resourceId
    data
    createdAt
  }
}

Ready to Try Our GraphQL API?

Explore our GraphQL API interactively, run queries, and see live responses.