0
0
GraphqlDebug / FixBeginner · 3 min read

How to Fix 'Expected Type but Got' Error in GraphQL

The 'expected type but got' error in GraphQL happens when the data you provide does not match the type defined in your schema. To fix it, ensure your query or mutation inputs exactly match the expected types, including nullability and list structure, using correct syntax and values.
🔍

Why This Happens

This error occurs because GraphQL expects a specific type for a field or argument, but the query or mutation provides a different type. This mismatch can be due to wrong data types, missing required fields, or incorrect list formats.

graphql
type Query {
  getUser(id: ID!): User
}

type User {
  id: ID!
  name: String!
}

# Query with wrong type for id (should be ID, given as Int)
{
  getUser(id: 123) {
    id
    name
  }
}
Output
Error: Expected type ID!, found 123.
🔧

The Fix

Change the input to match the expected type exactly. For example, if the schema expects an ID! type, provide a string value or quoted ID. Also, ensure lists and nullability match the schema.

graphql
type Query {
  getUser(id: ID!): User
}

type User {
  id: ID!
  name: String!
}

# Correct query with id as a string
{
  getUser(id: "123") {
    id
    name
  }
}
Output
{ "data": { "getUser": { "id": "123", "name": "Alice" } } }
🛡️

Prevention

To avoid this error, always check your schema types before writing queries or mutations. Use GraphQL tools like IDE plugins or linters that validate your queries against the schema. Also, be mindful of required fields and list formats.

⚠️

Related Errors

Similar errors include Cannot query field when a field does not exist, or Variable "$var" got invalid value when variables have wrong types. Fix these by matching schema definitions and using correct variable types.

Key Takeaways

Always match your query or mutation inputs to the exact types defined in your GraphQL schema.
Use quotes for ID and String types and ensure lists and nullability are correct.
Validate queries with GraphQL IDEs or linters to catch type mismatches early.
Read error messages carefully to identify which field or argument has the wrong type.