Part 4: GraphQL Client Development — TypeScript and Python

Consuming a GraphQL API from Two Worlds

Part 3 built the server. Now we write the clients.

This part covers two contexts I work with regularly:

  1. TypeScript client — a Node.js service (or frontend) that queries the product service using Apollo Client and type-safe code generation

  2. Python microservice client — a Python FastAPI service that calls the TypeScript GraphQL API as part of a larger microservices topology

Both scenarios are real patterns from my own projects. The Python service is an analytics or reporting service that needs product data but is not itself a GraphQL server (yet — federation in Part 6).

TypeScript: Apollo Client with Code Generation

Why Code Generation

Without code generation, you write queries as raw strings and get any back:

const result = await client.query({ query: gql`...` });
result.data.products.edges[0].node.name; // type: any — no IDE support, no compile errors

With GraphQL Code Generator, the query's return type is inferred exactly:

const result = await client.query<ProductsQuery, ProductsQueryVariables>({ query: ProductsDocument });
result.data?.products.edges[0].node.name; // type: string — fully typed

Setup

Code Generator Config

Add to package.json:

Write Queries as .graphql Files

Run npm run codegen to generate src/generated/graphql.ts with all types.

Apollo Client Instance

The typePolicies section configures cursor pagination merging — when a query fetches the next page, Apollo Client appends the edges to the existing list.

Using Generated Hooks (React)

Node.js Client (Non-React)

For a microservice that uses the GraphQL API without React:

Python: gql Client

The Python gql library provides a GraphQL client that works with any GraphQL server. I use it in Python microservices that need to fetch data from a TypeScript GraphQL service.

Installation

Basic Query

Async Client with FastAPI

Wiring into FastAPI

Python Subscriptions with WebSocket Transport

For a Python service that needs real-time updates:

Error Handling

Comparing Client Approaches

Aspect

TypeScript Apollo Client

Python gql

Type safety

Full — via code generation

Manual — use Pydantic models

Caching

Built-in normalized cache

No built-in cache

Subscriptions

via graphql-ws link

via WebSocket transport

Code generation

@graphql-codegen/cli

n/a

Best for

React apps, Node services

Python microservices, scripts

Auth headers

Apollo link chain

Transport headers

What's Next

You now know how to consume a GraphQL API from both TypeScript (with full type generation) and Python (using gql + Pydantic models).

In Part 5, we secure the API — adding JWT authentication to the Apollo context, implementing field-level authorization, and protecting subscriptions.

Last updated