# How to expose an existing REST API through a GraphQL gateway

> Put a GraphQL gateway in front of a REST API you cannot change, with its list as a connection, its 4xx responses in the errors array, and nested queries batched.

Source: https://voxgig.com/howto/expose-a-rest-api-through-graphql

- Audience: api-producer
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Write a GraphQL schema for the shape clients want, and resolvers that call the REST API. Turn a list endpoint and its next cursor into a connection whose edge cursors name the REST page and an index. Throw a GraphQLError with a code for each 4xx so it lands in the errors array. Batch nested fields with DataLoader against a bulk endpoint, or each parent costs one more REST call.

---
## You will need

An OpenAPI 3 document for the REST API, and Node 22.15 or later, which
`@graphql-hive/gateway-runtime` 3.0.0 asks for. Verified 2026-11-30 against Node 22.23.5,
`graphql` 16.15.0, `dataloader` 2.2.3, and GraphQL Mesh Compose 1.8.4. The sample's REST API is a
stand-in on 127.0.0.1, held to its `openapi.json`: a paged `/authors`, `/authors/{id}`,
`/authors/{id}/books`, and a bulk `/books?authorId=` that takes up to 50 ids.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Apollo Connectors](https://www.apollographql.com/docs/graphos/connectors) | You already run Apollo Router and federation, with a GraphOS plan | A GraphOS account to run the router, and has-many fields that usually cannot batch | You have no GraphOS account, or the gateway must run anywhere |
| [GraphQL Mesh OpenAPI source](https://the-guild.dev/graphql/mesh/v1/source-handlers/openapi) | Many REST operations, and a schema that mirrors them is acceptable | Operation names, REST pages, and status unions copied into the schema as the document has them | Clients need connections or a schema shaped unlike the REST paths |
| [Hand-written resolvers](https://graphql.org/learn/execution/) | A few resources, and the schema should read as GraphQL | A second API to keep in step with the REST one, by hand, field by field | The REST API has dozens of operations and changes often |

Mesh stood up the whole document from one configuration file and kept every REST wart, including
the operation ids as field names and a page object in place of a connection. Hand-written
resolvers gave the connection and the error codes asked for here, at the price of code for every
field. Apollo Connectors declare each field's REST call in the schema, and report a non-200 response as
a `CONNECTOR_FETCH` error by
[default](https://www.apollographql.com/docs/graphos/connectors/responses/error-handling). They run
in Apollo's router, and the
[Connectors quickstart](https://www.apollographql.com/docs/graphos/connectors/getting-started)
lists "A GraphOS Studio account" first among its prerequisites.

## Page the REST list as a connection

The REST list returns `{ items, nextCursor }`. A
[connection](https://relay.dev/graphql/connections.htm) needs a cursor on every edge, so each edge
cursor here encodes the REST page cursor and the item's index in that page.

```ts title="gateway.mjs"
export async function authorsConnection({ first, after }, rest) {
  if (!Number.isInteger(first) || first < 1 || first > 50) {
    throw new GraphQLError('first must be 1 to 50', { extensions: { code: 'BAD_USER_INPUT' } })
  }
  const start = after ? decodeCursor(after) : { c: null, i: -1 }
  let cursor = start.c
  let skip = start.i + 1
  const edges = []
  for (;;) {
    const page = await ok(rest.listAuthors({ limit: Math.min(50, skip + first - edges.length), cursor }))
    for (let i = skip; i < page.items.length && edges.length < first; i++) {
      const last = i === page.items.length - 1
      const edgeCursor = last && page.nextCursor !== null ? encodeCursor(page.nextCursor, -1) : encodeCursor(cursor, i)
      edges.push({ cursor: edgeCursor, node: page.items[i], last })
    }
    if (edges.length === first) {
      const hasNextPage = !edges.at(-1).last || page.nextCursor !== null
      return { edges, pageInfo: { hasNextPage, endCursor: edges.at(-1).cursor } }
    }
    if (page.nextCursor === null) return { edges, pageInfo: { hasNextPage: false, endCursor: edges.at(-1)?.cursor ?? null } }
    skip = Math.max(0, skip - page.items.length)
    cursor = page.nextCursor
  }
}
```

The last edge of a page carries the next REST page cursor with index -1, so `endCursor` resumes
with one REST call and no skipped rows. A cursor from mid-page fetches that page again and skips the
items before it. The REST limit stays within the 50 the document allows.

`query.mjs` runs each query through the gateway over HTTP and prints the REST calls the stand-in
received for it. The resolvers call REST over `node:http` rather than `fetch`, so a proxy set in the
environment never receives a call for 127.0.0.1.

```bash
node query.mjs
```

```text output
authors(first: 3)
{
  "data": {
    "authors": {
      "edges": [
        {"cursor":"W251bGwsMF0","node":{"name":"Author 1"}},
        {"cursor":"W251bGwsMV0","node":{"name":"Author 2"}},
        {"cursor":"WyJjMyIsLTFd","node":{"name":"Author 3"}}
      ],
      "pageInfo": {"hasNextPage":true,"endCursor":"WyJjMyIsLTFd"}
    }
  }
}
REST calls: 1
  GET /authors?limit=3
```

The next query, with `after` set to that `endCursor`, sends `GET /authors?limit=3&cursor=c3`.

## Put REST errors in the errors array

Each REST status maps to an error code a client can switch on, with the upstream status beside
it. A 5xx body stays in the gateway, so a client never reads an internal message.

```ts title="gateway.mjs"
export function restError({ status, body }) {
  const code = status === 404 ? 'NOT_FOUND' : status >= 400 && status < 500 ? 'BAD_USER_INPUT' : 'UPSTREAM_ERROR'
  const message = status < 500 && typeof body?.error === 'string' ? body.error : 'the upstream API failed'
  return new GraphQLError(message, { extensions: { code, upstreamStatus: status } })
}
```

The [GraphQL specification](https://spec.graphql.org/September2025/#sec-Handling-Execution-Errors)
says an error raised while resolving a field makes that position null and adds the error to the
`errors` list. A nullable field keeps the rest of the response.

```bash
node query.mjs
```

```text output
a 404 from REST
{
  "errors": [
    {
      "message": "author not found",
      "locations": [{"line":1,"column":3}],
      "path": ["missing"],
      "extensions": {"code":"NOT_FOUND","upstreamStatus":404}
    }
  ],
  "data": {"missing":null,"found":{"name":"Author 2"}}
}
REST calls: 2
  GET /authors/a404
  GET /authors/a2
```

`authors` is non-null in this schema, so a REST 400 on it nulls the whole `data`, as the same run
shows for a page cursor the REST API rejects.

## Batch the nested books

`Author.books` calls `/authors/{id}/books` once per author unless something collects the ids
first. [DataLoader](https://github.com/graphql/dataloader) collects every `load` from one tick of
execution and calls the batch function once.

```ts title="gateway.mjs"
function booksLoader(rest, batch) {
  if (!batch) return { load: (id) => ok(rest.listAuthorBooks(id)) }
  return new DataLoader(
    async (ids) => {
      const books = await ok(rest.listBooksByAuthors([...ids]))
      return ids.map((id) => books.filter((b) => b.authorId === id))
    },
    { maxBatchSize: 50 },
  )
}
```

The batch function must return one entry per id, in the order given, so the books are grouped
back by `authorId`. `maxBatchSize` matches the bulk endpoint's limit of 50.

```bash
node query.mjs
```

```text output
nested books, one REST call per author
10 authors, 19 books
REST calls: 11
  GET /authors?limit=10
  GET /authors/a1/books
  GET /authors/a2/books
  GET /authors/a3/books
  GET /authors/a4/books
  GET /authors/a5/books
  GET /authors/a6/books
  GET /authors/a7/books
  GET /authors/a8/books
  GET /authors/a9/books
  GET /authors/a10/books

nested books, batched through GET /books
10 authors, 19 books
REST calls: 2
  GET /authors?limit=10
  GET /books?authorId=a1&authorId=a2&authorId=a3&authorId=a4&authorId=a5&authorId=a6&authorId=a7&authorId=a8&authorId=a9&authorId=a10

same data both ways: true
```

## Generate the schema from the document instead

`generate.sh` runs `mesh-compose` on `mesh.config.ts`, which loads `openapi.json` through
`loadOpenAPISubgraph` from `@omnigraph/openapi`, and commits the composed schema. `mesh.mjs` serves it
in process with `@graphql-hive/gateway-runtime` against the same stand-in.

```bash
node mesh.mjs
```

```text output
generated types, directives removed
  type Query {
    listAuthors(limit: PositiveInt = 10, cursor: String): listAuthors_response
    getAuthor(id: String!): getAuthor_response
    listAuthorBooks(id: String!): [listAuthorBooks_response]
    listBooksByAuthors(authorId: [String]!): [listBooksByAuthors_response]
  }
  type AuthorPage {
    items: [Author]!
    nextCursor: String
  }
  type Author {
    id: String!
    name: String!
    books: [listAuthorBooks_response]
  }

a 404 the document declares
{"data":{"getAuthor":{"error":"author not found"}}}
REST calls: 1  GET /authors/a404

a 503 it does not declare
{"errors":[{"message":"Upstream HTTP Error: 503, Could not invoke operation GET /authors/{args.id}","path":["getAuthor"],"extensions":{"code":"DOWNSTREAM_SERVICE_ERROR","serviceName":"Library","request":{"url":"http://127.0.0.1:39333/authors/down","method":"GET"},"response":{"status":503,"statusText":"Service Unavailable","headers":["connection","content-type","date","transfer-encoding"],"body":{"error":"maintenance"}}}}],"data":{"getAuthor":null}}
REST calls: 1  GET /authors/down
```

With the packages this sample pins and this document, the fields are the operation ids, and each
result is a union of the 200 type and the declared error type. A declared 404 arrives as data. A
status the document leaves out becomes an error with the code `DOWNSTREAM_SERVICE_ERROR`, as Mesh's
[error handling page](https://the-guild.dev/graphql/mesh/v1/error-handling) describes. That error
hands the client the REST API's internal URL, the response headers, and the response body.

None of the eight transforms on Mesh's [transforms index](https://the-guild.dev/graphql/mesh/v1/transforms)
builds a connection: prefix, rename, naming convention, filter schema, hoist field, encapsulate,
prune, and federation. For a field that delegation cannot express, the schema extensions page
points to a custom resolver in `gatewayConfig.additionalResolvers`, which is the hand-written path
again.

## Keep the upstream address out of Mesh errors

The gateway runtime sends that `DOWNSTREAM_SERVICE_ERROR` to the client as Mesh built it.
`hideUpstreamDetails` in `mesh-run.mjs` is a plugin that rebuilds each error that carries an
upstream request or response, keeping a code and the upstream status.

```ts title="mesh-run.mjs"
export function hideUpstreamDetails() {
  const clean = (error) => {
    const ext = error.extensions ?? {}
    if (!ext.request && !ext.response && ext.code !== 'DOWNSTREAM_SERVICE_ERROR') return error
    return new GraphQLError('the upstream API failed', {
      nodes: error.nodes,
      source: error.source,
      positions: error.positions,
      path: error.path,
      extensions: { code: 'DOWNSTREAM_SERVICE_ERROR', upstreamStatus: ext.response?.status ?? null },
    })
  }
  return {
    onExecute: () => ({
      onExecuteDone: ({ result, setResult }) => {
        if (Symbol.asyncIterator in result) throw new Error('hideUpstreamDetails handles single results only')
        if (result.errors) setResult({ ...result, errors: result.errors.map(clean) })
      },
    }),
  }
}
```

Add it to the runtime's `plugins` list. `mesh.mjs` sends the same 503 through it.

```bash
node mesh.mjs
```

```text output
the same 503, through hideUpstreamDetails
{"errors":[{"message":"the upstream API failed","path":["getAuthor"],"extensions":{"code":"DOWNSTREAM_SERVICE_ERROR","upstreamStatus":503}}],"data":{"getAuthor":null}}
REST calls: 1  GET /authors/down
```

The plugin handles single results only, and throws on a streamed one, so a gateway that serves
`@defer` needs the same rewrite in each increment.

## Check it worked

The tests walk the whole list through the connection, resume after every edge, refuse bad cursors
before any REST call, and assert the REST call counts with and without batching.

```bash
node --test graphql.test.mjs
```

```text output
1..10
# tests 10
# suites 0
# pass 10
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 1651.518463
```

## When it goes wrong

A nested query is slow and the REST API's rate limit trips. Each parent sends its own REST call,
the N+1 problem moved onto HTTP. Batch with DataLoader against a bulk endpoint, or ask the REST
owners for one.

Mesh returns an `Error` object in place of the books of every author in a list. The `books` field
comes from an OpenAPI link on `getAuthor`, filled from `$response.body#/id`. On the pinned
packages, the gateway attaches that response only to the object an operation returned at its top
level. An author inside the `listAuthors` page has none, so each call goes out with an empty id:

```bash
node mesh.mjs
```

```text output
books through the link, from a list of three
{"data":{"listAuthors":{"items":[{"name":"Author 1","books":[{"error":"not found"}]},{"name":"Author 2","books":[{"error":"not found"}]},{"name":"Author 3","books":[{"error":"not found"}]}]}}}
REST calls: 4  GET /authors?limit=3  GET /authors//books  GET /authors//books  GET /authors//books

booksBatched, added with @resolveTo
{"data":{"listAuthors":{"items":[{"name":"Author 1","booksBatched":[{"title":"Book 1 by Author 1"}]},{"name":"Author 2","booksBatched":[{"title":"Book 1 by Author 2"},{"title":"Book 2 by Author 2"}]},{"name":"Author 3","booksBatched":[{"title":"Book 1 by Author 3"},{"title":"Book 2 by Author 3"},{"title":"Book 3 by Author 3"}]}]}}}
REST calls: 2  GET /authors?limit=3  GET /books?authorId=a1&authorId=a2&authorId=a3
```

The fix in Mesh is `mesh.batched.config.ts`: a field added with `@resolveTo`, keyed on `id`, sent
as `authorId` to the bulk operation, and matched back by `valueKeyField`, as the
[schema extensions page](https://the-guild.dev/graphql/mesh/v1/schema-extensions#batch-delegation-array-batching)
documents.

## When not to do this

Do not hand-write resolvers for a REST API with dozens of operations that changes every sprint.
Generating with Mesh keeps the schema in step with the document, and the REST shape is the price.

Do not put a gateway in front at all when one client needs one resource. A typed REST client
generated from the same OpenAPI document gives that client types without a second server to run.

Do not choose Apollo Connectors to escape the N+1 problem on a has-many field such as
`Author.books`. Its [batching page](https://www.apollographql.com/docs/graphos/connectors/requests/batching)
says such a relationship usually cannot be batched, and running it needs a GraphOS plan.[^1]

## Related how-tos

- [Implement Relay connections in a GraphQL schema](/howto/implement-relay-connections-in-a-schema)

- [Translate upstream API errors behind your own API](/howto/translate-upstream-errors-behind-your-api)

- [Retire a GraphQL field without versioning the schema](/howto/deprecate-graphql-fields-instead-of-versioning)

## Last verified

Verified 2026-11-30 against Node 22.23.5, `graphql` 16.15.0, `dataloader` 2.2.3,
`@graphql-hive/gateway-runtime` 3.0.0, `@graphql-mesh/compose-cli` 1.8.4, and `@omnigraph/openapi`
0.112.7. Every output block is what the command preceding it printed. Apollo Connectors were not
run, because the router needs a GraphOS account. What the page says of them comes from their
getting started, batching, and error handling pages.

[^1]: The [Connectors quickstart](https://www.apollographql.com/docs/graphos/connectors/getting-started)
lists two errors a first run can print. One reads "Not connected to GraphOS" and asks for the
`APOLLO_KEY` and graph ref. The other, "License not found," means a GraphOS account with a current
Free or Enterprise plan is needed.