When a movie landing page needs movie details, actors, and related films, a GraphQL query lets the consumer request that structure in one call. Unlike REST endpoints with fixed response shapes, the query specifies the fields to return, reducing under-fetching and over-fetching. section 7.1
A query must follow the GraphQL schema. It names an operation, selects fields such as id, name, and year, and can pass variables such as a required movieId. Resolvers then obtain the requested data; selecting a field absent from the schema causes the query to fail. section 7.1 section 7.2.3
A practical consumer query can:
- Fetch all movies with a MoviesQuery operation and request only id, name, and year. section 7.2.3
- Fetch one movie with a Movie operation and supply movieId as a variable. section 7.2.3
- Use Apollo Client to send the query to the GraphQL endpoint and handle returned data or errors. section 7.2.3
Querying a movie list
query MoviesQuery { movies { id name year } } requests a list with exactly those fields. A contract interaction can record the query, operation name, variables, endpoint, status, headers, and response shape; matchers can check types without requiring fixed values. section 7.3.3
Figure 7.2 A web consumer making a single query to a GraphQL endpoint to retrieve all the data they require
Compare the single GraphQL request with the multiple REST requests needed to assemble the same consumer data. section 7.1
const getMovies = async () => {
const response = await client
.query({
query: gql`
query MoviesQuery { #1
movies { #1
id #1
name #1
year #1
} #1
} #1
`, #1
})
.then((result) => result.data)
.catch((err) => err.response);
return response;
};
const getMovieById = async (movieId) => {
const response = await client
.query({
query: gql`
query Movie($movieId: Int!) { #2
movie(movieId: $movieId) { #2
id #2
name #2
year #2
} #2
} #2
`, #2
variables: {
movieId,
},
})
.then((result) => result.data)
.catch((err) => err.response);
return response;
};
module.exports = {
getMovies,
getMovieById,
};
Inspect client-side query definitions for list retrieval and variable-based single-movie retrieval. section 7.2.3

