# GraphQL API

> Source: https://agilitycms.com/docs/developers/graphql-api

Every Agility instance has a GraphQL API alongside the REST Content Fetch API. Its schema is generated from your content models, so each content list you create is immediately queryable, with a type for every field. It serves both published and staging (preview) content, in every locale.

Compared with the Content Fetch (REST) API, GraphQL gives you:

- Full control over which fields are returned
- Several queries in one request
- Linked content resolved inline, with filtering and sorting on related content
- A typed schema that tools can generate TypeScript types from

> [!NOTE]
> This article covers calling the Agility GraphQL API directly. For end-to-end TypeScript types in a Next.js site, see [Typed GraphQL with TypeScript and Next.js](https://agilitycms.com/docs/developers/typed-graphql-typescript-nextjs).

## What is GraphQL?

Created by Facebook in 2012 and open-sourced in 2015, GraphQL is a query language for APIs. The client describes exactly the data it needs, and the response has exactly that shape: no over- or under-fetching, and data from several sources in a single request.

This 30-second clip from our friends at Shopify shows the difference from a traditional REST API:

<iframe width="580" height="320" src="https://www.youtube.com/embed/7MroZIBz7v8" title="GraphQL vs REST" frameborder="0" allowfullscreen></iframe>

## Why use GraphQL with Agility

- **Ask for exactly the fields you need.** A listing can request titles and URLs only, instead of whole items.
- **One request for several lists.** Fetch alerts, locations and site settings in a single round trip.
- **Linked content in the same query.** Request the fields of a linked item inline instead of making a second call.
- **A typed contract.** The schema describes every list and field, so a renamed or removed field can be caught at build time instead of in production.
- **Any front end.** It's plain HTTP and JSON: any language or framework, or a static page with `fetch`.

## Endpoint and authentication

```
POST https://api.aglty.io/v1/{instance-guid}/{fetch|preview}/{locale}/graphql
```

| Part | Value |
| --- | --- |
| `fetch` / `preview` | `fetch` returns published content; `preview` returns the latest staging version |
| `{locale}` | A locale code from your instance, such as `en-us`. Each locale has its own endpoint |
| Header | `apikey: <your API key>`. Use the **Fetch** key with `fetch` and the **Preview** key with `preview` |

Find your instance GUID and API keys in **Settings > API Keys**.

> [!TIP]
> The GraphQL endpoint uses `/v1/` and the `apikey` header; the REST Fetch API uses neither (`https://api.aglty.io/{guid}/fetch/{locale}/...` with an `APIKey` header). A request to a route that doesn't exist returns `Invalid API type (must be fetch or preview)`, which means the URL is wrong, not the key.

```javascript
const res = await fetch(`https://api.aglty.io/v1/${guid}/fetch/en-us/graphql`, {
  method: "POST",
  headers: { "Content-Type": "application/json", apikey: fetchApiKey },
  body: JSON.stringify({
    query: `{
      offices(take: 50, sort: "fields.city") {
        contentID
        fields { title city zip }
      }
    }`,
  }),
})
const { data, errors } = await res.json()
```

## What's in the schema

| Root field | Returns |
| --- | --- |
| One field per content list, named after the list's reference name in lower case (for example `offices`, `newsreleases`) | The list's items: `contentID`, `properties` (`versionID`, `modified`, `state`, `itemOrder`...), `seo`, and `fields`, with one typed field per model field |
| `ag_sitemapflat(channelName)` | The flat sitemap: `path`, `pageID`, `title`, `menuText`, `visible`, `redirecturl`, `isFolder` |
| `ag_sitemapnested(channelName)` | The nested sitemap |
| `ag_pages(pageID)` | Pages: `name`, `path`, `title`, `menuText`, `templateName`, `seo`, `visible`, `dynamic`, `properties` and `zones` |
| `ag_urlredirections` | URL redirections: `originUrl`, `destinationUrl`, `statusCode` |

Things to know:

- **Fields are nullable.** Every field in the generated schema is nullable, so handle `null` (for example, an optional field left blank).
- **Page components are untyped.** A page's `zones` return each component's `module` name and its `item.fields` as `JSON`. Content lists are fully typed; the fields of components placed on pages are not. For typed component data, read it with the Fetch API or query the content list it links to.
- **The schema follows your models.** Add a field to a model and it appears in the schema. If you generate types from the schema, re-run the generator when models change.

## Explore the GraphQL playground

Every instance has a GraphQL playground for trying queries. Go to **Settings > API Keys** and click **Explore GraphQL API**.

Update the endpoint URL with your locale and `fetch` or `preview`:

![GraphQL API URL in the Agility GraphQL playground](https://cdn.aglty.io/agility-cms-docs/block-editor/developerarticles/Screen_Shot_2021-07-15_at_11.23.44_AM-09212021211601.png)

Then click **Set Headers** and add your API key as the `apikey` header. Use the **Fetch** key for published content and the **Preview** key for staging content:

![Adding the API key as a header in the GraphQL playground](https://cdn.aglty.io/agility-cms-docs/block-editor/developerarticles/Screen_Shot_2021-07-15_at_11.33.51_AM-09212021211601.png)

![Choosing the Fetch or Preview API key](https://cdn.aglty.io/agility-cms-docs/block-editor/developerarticles/Screen_Shot_2021-07-15_at_11.34.24_AM-09212021211601.png)

Click **Save**, then **Reload** to load the schema:

![Reloading the GraphQL schema in the playground](https://cdn.aglty.io/agility-cms-docs/block-editor/developerarticles/Screen_Shot_2021-07-15_at_11.49.48_AM-09212021211601.png)

Open **Docs** and click **Root** to see everything you can query in your instance.

## Paging, sorting and filtering

List fields take `take`, `skip`, `sort`, `direction` and `filter`, plus `contentID` to get a single item:

```graphql
{
  articles(take: 10, skip: 0, sort: "fields.date", direction: "desc", filter: "fields.title[like]\"Person\"") {
    contentID
    properties { versionID }
    fields { title date }
  }
}
```

`filter` uses the same operators as the REST API (`eq`, `ne`, `lt`, `gt`, `in`, `contains`, `like`, with `AND` / `OR` and parentheses). See [GraphQL & Rest API Filtering](https://agilitycms.com/docs/developers/graphql-operators).

## Preview and caching

- Use the `preview` endpoint and Preview key only for preview sessions, and don't cache those responses.
- Cache published responses in your front end, and clear them from Agility's publish [webhook](https://agilitycms.com/docs/developers/webhooks), as you would for the Fetch API. Tag each cached query with the content lists it reads so one webhook handler serves both APIs.
- The Fetch key returns only published content, but keep it server-side where you can. If a page calls GraphQL from the browser, the key is visible in the page source.

## GraphQL or the Fetch API?

| Use GraphQL when | Use the Fetch API / SDK when |
| --- | --- |
| You want typed, field-level control over content lists | You're rendering pages and their components (the SDKs handle this) |
| One view needs several lists at once | You need the Content Sync API or the SDKs' page helpers |
| You're building outside JavaScript, or without an SDK | The SDK already gives you what you need |

Most sites use both: the SDK for pages, and GraphQL for typed content lists.

## Further reading

- [Typed GraphQL with TypeScript and Next.js](https://agilitycms.com/docs/developers/typed-graphql-typescript-nextjs)
- [GraphQL & Rest API Filtering](https://agilitycms.com/docs/developers/graphql-operators)
- [Content Fetch API](https://agilitycms.com/docs/developers/content-fetch-api)
- [Webhooks](https://agilitycms.com/docs/developers/webhooks)

---

## Related pages

- [Content Fetch API](https://agilitycms.com/docs/developers/content-fetch-api.md)
- [Content Sync API](https://agilitycms.com/docs/developers/content-sync-api.md)
- [Content Management API](https://agilitycms.com/docs/developers/content-management-api.md)
- [CLI - CI/CD Integration Guide](https://agilitycms.com/docs/developers/cli-ci-cd-integration-guide.md)
- [Testing on Swagger](https://agilitycms.com/docs/developers/testing-on-swagger.md)
- [GraphQL & Rest API Filtering](https://agilitycms.com/docs/developers/graphql-operators.md)
- [AgilityCLI (Command Line Interface)](https://agilitycms.com/docs/developers/cli.md)
- [Personal Access Tokens](https://agilitycms.com/docs/developers/personal-access-tokens.md)
- [Content Delivery & CDN Architecture](https://agilitycms.com/docs/developers/content-delivery-and-cdn-architecture.md)
- [Typed GraphQL with TypeScript and Next.js](https://agilitycms.com/docs/developers/typed-graphql-typescript-nextjs.md)
- [Image Transformation Reference](https://agilitycms.com/docs/developers/image-transformation-reference.md)
- [Fetch API Status Codes and Caching](https://agilitycms.com/docs/developers/fetch-api-status-codes-and-caching.md)
- [Field Types and What the APIs Return](https://agilitycms.com/docs/developers/field-types-api-reference.md)
- [Content Sync Explained](https://agilitycms.com/docs/developers/content-sync-explained.md)
- [Agility CLI Command Reference](https://agilitycms.com/docs/developers/cli-reference.md)
- [CLI Reference: agility pull](https://agilitycms.com/docs/developers/cli-pull.md)
- [CLI Reference: agility sync and push](https://agilitycms.com/docs/developers/cli-sync.md)
- [CLI Reference: agility reverse-sync](https://agilitycms.com/docs/developers/cli-reverse-sync.md)
- [CLI Reference: agility workflows](https://agilitycms.com/docs/developers/cli-workflows.md)
- [CLI Reference: agility login and logout](https://agilitycms.com/docs/developers/cli-login-logout.md)
- [Test Your Agility Integration in CI](https://agilitycms.com/docs/developers/test-agility-integration-in-ci.md)
- [CLI Reference: agility verify](https://agilitycms.com/docs/developers/cli-verify.md)
- [Create a Personal Access Token with the API](https://agilitycms.com/docs/developers/create-personal-access-token.md)
- [Manage Personal Access Tokens in Agility](https://agilitycms.com/docs/developers/manage-personal-access-tokens.md)

Index of every docs page: https://agilitycms.com/docs/llms.txt
