Bird
Raised Fist0
GraphQLquery~10 mins

Data source integration in GraphQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Data source integration
Start: Define GraphQL Schema
↓
Connect to Data Source
↓
Write Resolvers
↓
Query Execution
↓
Fetch Data from Source
↓
Return Data to Client
This flow shows how GraphQL connects to a data source, fetches data, and returns it to the client.
Execution Sample
GraphQL
type Query {
  book(id: ID!): Book
}

const resolver = {
  Query: {
    book: (parent, args) => fetchBookById(args.id)
  }
};
Defines a query to get a book by ID and resolver fetches data from the data source.
Execution Table
StepActionInputProcessOutput
1Receive Query{ book(id: "1") }Parse queryQuery object with id=1
2Call Resolverid=1Invoke fetchBookById(1)Call to data source
3Fetch Dataid=1Query database or API{ id: "1", title: "GraphQL Guide" }
4Return DataBook objectFormat response{ book: { id: "1", title: "GraphQL Guide" } }
💡 Data fetched and returned to client, query execution complete.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
querynull{ book(id: "1") }{ book(id: "1") }{ book(id: "1") }{ book(id: "1") }
args.idnullnull111
datanullnullnull{ id: "1", title: "GraphQL Guide" }{ id: "1", title: "GraphQL Guide" }
responsenullnullnullnull{ book: { id: "1", title: "GraphQL Guide" } }
Key Moments - 3 Insights
Why does the resolver receive 'args' with the id value?
Because the query includes an argument 'id', the GraphQL server parses it and passes it as 'args' to the resolver, as shown in step 2 of the execution_table.
How does the resolver know where to get the data from?
The resolver contains the logic to fetch data from the data source, like a database or API, demonstrated in step 3 where fetchBookById is called.
What happens if the data source returns no data?
The resolver would return null or an empty object, and the response would reflect that, stopping at step 4 with no book data.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output after step 3?
A{ book: { id: "1", title: "GraphQL Guide" } }
B{ id: "1", title: "GraphQL Guide" }
CQuery object with id=1
DCall to data source
💡 Hint
Check the 'Output' column in row with Step 3 in execution_table.
At which step does the resolver function get called?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in execution_table where resolver is invoked.
If the query had no 'id' argument, what would change in the variable_tracker?
Aargs.id would be null or undefined
Bdata would be fetched with id=1 anyway
Cresponse would be empty
Dquery would be null
💡 Hint
Refer to 'args.id' row in variable_tracker and consider missing argument.
Concept Snapshot
GraphQL Data Source Integration:
- Define schema with queries and types
- Write resolvers to fetch data
- Resolver receives args from query
- Resolver calls data source (DB/API)
- Data returned to client in query shape
Full Transcript
This visual execution shows how GraphQL integrates with a data source. First, the GraphQL server receives a query requesting a book by ID. It parses the query and calls the resolver function with the argument 'id'. The resolver then fetches the book data from the data source, such as a database or API. Finally, the data is returned formatted as the query expects. Variables like 'args.id' and 'data' change step-by-step during execution. Key moments include understanding how arguments reach resolvers and how data is fetched. The quiz tests understanding of these steps.

Practice

(1/5)
1. What is the main purpose of data source integration in GraphQL?
easy
A. To style the GraphQL interface for better user experience
B. To encrypt data sent over the network
C. To create new GraphQL schema types automatically
D. To connect GraphQL queries to the actual data storage or services

Solution

  1. Step 1: Understand what data source integration means

    It means linking GraphQL queries to where data is stored or fetched from, like databases or APIs.
  2. Step 2: Identify the main goal of this integration

    The goal is to let GraphQL get data from these sources when a query runs.
  3. Final Answer:

    To connect GraphQL queries to the actual data storage or services -> Option D
  4. Quick Check:

    Data source integration = connect queries to data [OK]
Hint: Think: GraphQL needs to reach data somewhere [OK]
Common Mistakes:
  • Confusing integration with UI styling
  • Thinking it creates schema types automatically
  • Assuming it handles data encryption
2. Which of the following is the correct way to define a resolver that fetches data from a REST API in GraphQL?
easy
A. const resolver = () => fetch('https://api.example.com/data').then(res => res.json());
B. const resolver = fetch('https://api.example.com/data').json();
C. const resolver = () => fetch('https://api.example.com/data').json();
D. const resolver = () => fetch('https://api.example.com/data').then(res => res.text());

Solution

  1. Step 1: Check how fetch works in JavaScript

    fetch returns a promise; to get JSON, you call .then(res => res.json()).
  2. Step 2: Verify the resolver syntax

    const resolver = () => fetch('https://api.example.com/data').then(res => res.json()); correctly returns a function that fetches and parses JSON asynchronously.
  3. Final Answer:

    const resolver = () => fetch('https://api.example.com/data').then(res => res.json()); -> Option A
  4. Quick Check:

    fetch + then + json() = correct resolver [OK]
Hint: Remember fetch returns a promise; use then() to parse JSON [OK]
Common Mistakes:
  • Calling .json() directly on fetch without then()
  • Not wrapping fetch in a function
  • Using res.text() instead of res.json() for JSON data
3. Given this resolver code snippet, what will be the output of the GraphQL query if the API returns [{"id":1,"name":"Alice"}]?
const resolvers = {
  Query: {
    users: async () => {
      const response = await fetch('https://api.example.com/users');
      const data = await response.json();
      return data;
    }
  }
};
medium
A. undefined
B. {"id":1,"name":"Alice"}
C. [{"id":1,"name":"Alice"}]
D. Error: fetch is not defined

Solution

  1. Step 1: Analyze the resolver's return value

    The resolver awaits the fetch, parses JSON, and returns the data array as is.
  2. Step 2: Match the returned data with the query output

    The API returns an array with one user object, so the query returns the same array.
  3. Final Answer:

    [{"id":1,"name":"Alice"}] -> Option C
  4. Quick Check:

    Returned data array = output array [OK]
Hint: Async resolver returns exactly what API sends after parsing [OK]
Common Mistakes:
  • Assuming it returns a single object instead of an array
  • Forgetting async/await means data is resolved
  • Thinking fetch is undefined in server environment
4. Identify the error in this resolver code that fetches data from a database:
const resolvers = {
  Query: {
    products: () => {
      const data = db.query('SELECT * FROM products');
      return data;
    }
  }
};
medium
A. The resolver should be async and await the db query
B. The query string is incorrect SQL syntax
C. The resolver should return a promise, not data
D. The resolver is missing a try-catch block

Solution

  1. Step 1: Understand db.query behavior

    db.query usually returns a promise, so it must be awaited in async functions.
  2. Step 2: Check resolver function signature

    The resolver is not async and does not await the promise, so it returns a pending promise instead of data.
  3. Final Answer:

    The resolver should be async and await the db query -> Option A
  4. Quick Check:

    Async + await needed for promises [OK]
Hint: If db query returns promise, resolver must be async and await it [OK]
Common Mistakes:
  • Ignoring async/await for promises
  • Assuming SQL syntax is wrong without checking
  • Thinking try-catch is mandatory for correctness
5. You want to integrate two data sources in a GraphQL resolver: a REST API and a SQL database. Which approach correctly combines data from both sources before returning it?
const resolvers = {
  Query: {
    combinedData: async () => {
      const apiData = await fetch('https://api.example.com/items').then(res => res.json());
      const dbData = await db.query('SELECT * FROM items');
      // What next?
    }
  }
};
hard
A. Return {apiData, dbData} as an object without merging
B. Return [...apiData, ...dbData] to merge both arrays
C. Return dbData only, ignoring apiData
D. Return apiData only, ignoring dbData

Solution

  1. Step 1: Understand data types returned

    Both apiData and dbData are arrays of items fetched asynchronously.
  2. Step 2: Combine arrays before returning

    Using spread syntax [...apiData, ...dbData] merges both arrays into one list.
  3. Final Answer:

    Return [...apiData, ...dbData] to merge both arrays -> Option B
  4. Quick Check:

    Spread arrays to combine data sources [OK]
Hint: Use spread operator to merge arrays from multiple sources [OK]
Common Mistakes:
  • Returning only one data source ignoring the other
  • Returning an object without merging arrays
  • Forgetting to await both data sources
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard