The APIs · Lesson 6 of 15 · 10 min
Ask for exactly what you need with GraphQL
Run one query that returns a course, its lessons, and their authors, and learn when to pick GraphQL over REST.
The REST API in lesson 5 sends whole entries. GraphQL lets you list the exact fields you want and get back that shape, nothing more.
Contentful builds the GraphQL schema from your content model. You made a Course content type, so there’s a courseCollection query. No setup needed.
1. Run a query
curl -s "https://graphql.contentful.com/content/v1/spaces/$SPACE/environments/master" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"query":"{ courseCollection { items { title level lessonsCollection { items { title minutes author { name } } } } } }"}'
The same query, laid out so you can read it:
{
courseCollection {
items {
title
level
lessonsCollection {
items {
title
minutes
author {
name
}
}
}
}
}
}
The response has the same shape as the query. Course, lessons, authors, one request, no leftover fields.
How the names work
| In your model | In GraphQL |
|---|---|
Content type lesson |
Type Lesson, queries lesson and lessonCollection |
Field lessons (many references) |
lessonsCollection { items { ... } } |
Field author (one reference) |
author { ... } |
Field photo (media) |
photo { url description width height } |
Field body (rich text) |
body { json } |
2. Filter and sort
One lesson by slug:
{
lessonCollection(where: { slug: "my-first-lesson" }, limit: 1) {
items {
title
summary
}
}
}
Shortest lessons first:
{
lessonCollection(order: minutes_ASC) {
items {
title
minutes
}
}
}
REST or GraphQL?
| REST with the SDK | GraphQL | |
|---|---|---|
| Best for | Build-time fetching of everything | Apps that need a few fields, fast |
| Links | The SDK resolves them for you | You ask for them in the query |
| Payload | Whole entries | Only what you asked for |
| Limits to know | Paged results, 100 at a time by default | A complexity limit per query |
| Rich text | Resolved, ready for the renderer | JSON plus a separate links block you match up yourself |
This course uses REST with the SDK for the Astro site. You’re fetching everything once at build time, and the SDK’s link resolving saves real work with rich text. A phone app showing a lesson list would be a better fit for GraphQL.