# Fetching entries – Schema Builder

Read the schemas and one schema's entries through the Delivery API or GraphQL, with a sample Next.js project.

This page shows how a website reads Schema Builder data: the schemas from the Schema Registry entry, then the entries of one schema, through the Delivery API or GraphQL. The code comes from a working Next.js sample, so you can run it before you copy it.

## The sample project

`examples/schema-builder-next` lists the schemas, the entries of each schema and one entry laid out by its schema.

1. Publish the **Schema Registry** entry and a few entries in your space.
2. Copy `.env.example` to `.env.local`. Add your space ID and a Content Delivery API token. Set `CONTENTFUL_CONTENT_TYPE_ID` if your content type ID isn't `schemaBuilderEntry`.
3. Run `npm install`, then `npm run dev`, and open http://localhost:3006.

Without those variables the sample reads `src/lib/fixture.json`, a copy of the Fernhill Outdoor demo in the same shape as a Delivery API response, and shows a notice saying so.

## The Delivery API client

The sample uses Contentful's JavaScript SDK, the `contentful` package. Every request goes through one client. It runs on the server only, so the delivery token never reaches the browser. The pages render on every request, so a newly published entry shows at once.

```ts title="examples/schema-builder-next/src/lib/contentful.ts (trimmed)"
import { createClient } from "contentful";

const {
  CONTENTFUL_SPACE_ID,
  CONTENTFUL_DELIVERY_TOKEN,
  CONTENTFUL_ENVIRONMENT = "master",
  CONTENTFUL_CONTENT_TYPE_ID = "schemaBuilderEntry",
} = process.env;

const client = () =>
  createClient({
    space: CONTENTFUL_SPACE_ID ?? "",
    accessToken: CONTENTFUL_DELIVERY_TOKEN ?? "",
    environment: CONTENTFUL_ENVIRONMENT,
  });
```

The sample caches the schemas and each entry for 60 seconds with Next.js `unstable_cache`, so a published change can take up to a minute to show.

The sample asks for the default locale only, so each field comes back as a plain value, not keyed by locale. Filtering on `fields.type` works because the request doesn't use `locale=*`.

## Read the schemas

The schemas are the `jsonField` of the entry whose `type` is `SchemaRegistry`. The Delivery API only sees it once it's published, so publish it again after every schema change.

```ts title="examples/schema-builder-next/src/lib/contentful.ts (trimmed)"
const REGISTRY_TYPE = "SchemaRegistry";

/** The schemas, read from the published Schema Registry entry. Empty until the registry is published. */
export async function getRegistry(): Promise<Registry> {
  const [entry] = await entries({ "fields.type": REGISTRY_TYPE, limit: 1 }, (e) => e.fields.type === REGISTRY_TYPE);
  return (entry?.fields.jsonField as Registry | undefined) ?? { version: 3, schemas: [] };
}
```

`Registry` is in `src/lib/schema-builder/registry.ts`: the format the app saves (version 3), as TypeScript types.

## List the entries of one schema

Filter on `fields.type`, and never return the registry itself:

```ts title="examples/schema-builder-next/src/lib/contentful.ts (trimmed)"
/** Contentful filters by `type` or ID; the fixture is filtered in code with the same test. */
async function entries(
  query: Record<string, string | number>,
  match: (e: SchemaEntry) => boolean,
): Promise<SchemaEntry[]> {
  const { items } = isConfigured
    ? await client().getEntries({ content_type: CONTENTFUL_CONTENT_TYPE_ID, ...query })
    : fixture;
  return (items as unknown as SchemaEntry[]).filter(match);
}

// shortcut: one page of up to 1000 entries, page with `skip` if a schema has more than that.
export async function listEntries(schemaId: string): Promise<SchemaEntry[]> {
  if (schemaId === REGISTRY_TYPE) return [];
  const list = await entries({ "fields.type": schemaId, limit: 1000 }, (e) => e.fields.type === schemaId);
  return list.sort((a, b) => a.fields.title.localeCompare(b.fields.title));
}

export async function getEntry(id: string): Promise<SchemaEntry | undefined> {
  const [entry] = await entries({ "sys.id": id }, (e) => e.sys.id === id && e.fields.type !== REGISTRY_TYPE);
  return entry;
}
```

Contentful can filter on `type` and `title`, but not on values inside `jsonField`. To sort or filter by a value, fetch the schema's entries and do it in your own code. [When to use it](https://contentful.geeconglobal.com/apps/schema-builder/docs/when-to-use) covers when that's a problem.

## Linked assets and entries

Media and Reference values are links stored inside the JSON. Contentful doesn't resolve links inside a JSON field, so `include` won't expand them. Collect the IDs from the links, then fetch them by ID: `client().getAssets({ "sys.id[in]": ids })` for media and `client().getEntries({ "sys.id[in]": ids })` for references. A link can point at something unpublished or deleted, so handle a missing item.

## GraphQL

The same content type is available in Contentful's GraphQL API. With the default content type ID the collection is `schemaBuilderEntryCollection`, and `jsonField` comes back as plain JSON:

```graphql title="Entries of one schema"
query EntriesOfSchema($type: String!) {
  schemaBuilderEntryCollection(where: { type: $type }, order: title_ASC, limit: 100) {
    items {
      sys {
        id
      }
      title
      type
      jsonField
    }
  }
}
```

Run it with `{ "type": "faqItem" }` to get the FAQ entries. Ask for the registry the same way, with `"type": "SchemaRegistry"`. GraphQL doesn't resolve links inside `jsonField` either.

> **Things to know**
>
>
> - Publish the Schema Registry entry after each schema change, or read it through the Preview API.
> - Leave out the entry whose `type` is `SchemaRegistry` when you list entries.
> - The sample reads one page of up to 1,000 entries. Page with `skip` if a schema has more.
> - Next: [Types and validation](https://contentful.geeconglobal.com/apps/schema-builder/docs/types-and-validation), then [Rendering entries](https://contentful.geeconglobal.com/apps/schema-builder/docs/rendering).
>
