Using GraphQL Code Generator For Type-Safe GraphQL Clients
Tags: graphql, typescript
Published: 2020-11-12 14:20:52

---
title: Using GraphQL Code Generator For Type-Safe GraphQL Clients
published: true
description: Using GraphQL together with TypeScript can have huge advantages, as you can use your GraphQL schema to create TypeScript type definitions and even code that fetches data from the GraphQL server.
tags: GraphQL, TypeScript
canonical_url: https://www.newline.co/@royderks/using-graphql-code-generator-for-type-safe-graphql-clients--b3ccd108
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/kucusdm0w88sovwwucxi.png
---

Using GraphQL together with TypeScript can have huge advantages, as you can use your GraphQL schema to create TypeScript type definitions and even code that fetches data from the GraphQL server. 

> Want to know more about advanced GraphQL implementations? Have a look at my book [Fullstack GraphQL](https://newline.co/fullstack-graphql). {% twitter 1317026521274634240 %}

This is incredibly powerful. Why is that? Basically it means we can have TypeScript types that match our GraphQL types and operations. An important nuance is that TypeScript has a set of types and GraphQL has a set of types. It might take a minute to understand, but these are different things, as GraphQL and TypeScript have a similar type system with slightly different nuances. What exactly is what we will discover in this article!

## GraphQL API

To generate TypeScript type definitions and code from GraphQL, we first need to have a schema. For this you'll use the [Rick and Morty API](https://rickandmortyapi.com/documentation/) that is publicly available, and based on the popular television show.

When you open the GraphQL Playground for the Rick and Morty API you can use multiple operations like queries and mutations.

Let's try this out, by pasting the query below in the Explorer:

```graphql
{
  characters {
    results {
      name
      gender
    }
  }
}
```

This will result in a JSON response that consists of all the characters in the show and their `name` and `gender`.

![](https://s3.amazonaws.com/assets.fullstack.io/n/20201111184022740_screencapture-rickandmortyapi-graphql-2020-11-11-19_39_45.jpg)Great! Using the Rick and Morty API as starting point we can now use this with TypeScript and autogenerate some code.

## Requesting GraphQL from your App

To get this data from the GraphQL API into your application you need to fetch the data using the query. For this you could use a regular HTTP-request or any of the popular GraphQL clients. 

For this example we're using the library `[graphql-request](https://github.com/prisma-labs/graphql-request)` that's very lightweight and requires just a few lines of code. After installing it from NPM, you can fetch data from the Rick and Mory API like this:

```typescript
import { request, gql } from 'graphql-request';

const query = gql`
  {
    characters {
      results {
        name
        gender
      }
    }
  }
`;

request('https://rickandmortyapi.com/graphql/', query).then((data) =>
  console.log(data),
);
```

But the data that you receive from the API doesn't have any type definitions that you can use in TypeScript. Instead of adding them manually, the library GraphQL Code Generator can be used.

## GraphQL Code Generator 

Generating the TypeScript type definitions and code can be done with GraphQL Code Generator is a CLI tool that generates TypeScript typings out of any GraphQL schema. 

Let's create an application to fetch the Github info using TypeScript code generated from the GraphQL schema. Installing GraphQL Code Generator can be done with `npm` or Yarn, but first you need to add `graphql` as a dependency.

```bash
npm i graphql  
```

And `@graphql-codegen/cli` and related plugins as a dev dependency:

```bash
npm i --save-dev @graphql-codegen/cli @graphql-codegen/typescript
```

You've now installed everything you need to generate the type definitions from the GraphQL API. 

But to use GraphQL Code Generator you need to add a configuration file called `codegen.yaml` that specifies the url to the GraphQL API and the plugins that must be used:

```yaml
# codegen.yaml
schema: https://rickandmortyapi.com/graphql/
generates:
  ./src/types.ts:
    plugins:
      - typescript
```

After adding the configuration file you can run the command `graphql-codegen` from the command line, in the same directory as the configuration file was added. This will now create a new `types.ts` file containing all the TypeScript type definitions based on the schema of the Rick and Morty API.

This means that you can use this to have a type for the data returned by `graphql-request`. In your query you requested the characters that are represented as a type called `Characters`:

```typescript
import { request, gql } from 'graphql-request';
import { Characters } from './types';

const query = gql<code>
  {
    characters {
      results {
        name
        gender
      }
    }
  }
</code>;

request('https://rickandmortyapi.com/graphql/', query).then((data: { characters: Characters }) =>
  console.log(data),
);
```

Pretty straightforward! Of course, there are many more features GraphQL Code Generator that you could use. In the book [Fullstack GraphQL](https://newline.co/fullstack-graphql) you can find more working examples, including a guide to generate GraphQL client code from your GraphQL schema.