> ## Documentation Index
> Fetch the complete documentation index at: https://developers.drpn.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Schema and codegen

> Download the GraphQL schema as a .graphql file and generate a typed TypeScript client from it.

The schema is one SDL file. Download it once, point a code generator at it, and every query you write gets types checked against the API.

## Download the schema

Either route gives the same SDL for hosted Darpan.

**From the live API.** `GET /rest/s1/graphql/sdl` needs no key. It returns JSON with the SDL in one string field, `sdl`, so unwrap it:

```bash theme={null}
curl -s https://api.drpn.ai/rest/s1/graphql/sdl | jq -r .sdl > schema.graphql
```

A self-hosted instance serves the same path on its own backend URL. This is the schema the server is running now.

**From GitHub.** The schema these docs are generated from is committed as [`graphql-reference/schema.graphql`](https://github.com/drpn-ai/darpan-developers/blob/main/graphql-reference/schema.graphql):

```bash theme={null}
curl -s -o schema.graphql https://raw.githubusercontent.com/drpn-ai/darpan-developers/main/graphql-reference/schema.graphql
```

It is updated when the docs are regenerated, so it can trail a deploy by a short while. Use the live route when the two must match exactly.

> [!NOTE]
>
> Introspection (`__schema`, `__type`) is a query like any other: send it to `/graphql/public` with an API key. Without one it returns `UNAUTHENTICATED`. Only `/graphql/sdl` is open.

## Generate a typed TypeScript client

This uses [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) with its client preset.

1. Install it next to your code:

   ```bash theme={null}
   npm install --save-dev @graphql-codegen/cli@5 @graphql-codegen/client-preset@4 graphql typescript
   ```

2. Save `schema.graphql` in the project root, and add `codegen.ts`:

   ```ts codegen.ts theme={null}
   import type { CodegenConfig } from '@graphql-codegen/cli'

   const config: CodegenConfig = {
     schema: 'schema.graphql',
     documents: ['src/**/*.graphql'],
     generates: {
       'src/gql/': {
         preset: 'client',
         config: {
           scalars: { DateTime: 'string', Decimal: 'string' },
           enumsAsTypes: true,
         },
       },
     },
   }

   export default config
   ```

3. Write each query in its own `.graphql` file under `src/`:

   ```graphql src/morning.graphql theme={null}
   query Morning($audit: String!) {
     auditReport(audit: $audit) {
       health { complete summary }
       summary { open newToday }
     }
   }
   ```

4. Generate:

   ```bash theme={null}
   npx graphql-codegen --config codegen.ts
   ```

   `src/gql/graphql.ts` now holds `MorningDocument`, `MorningQuery` and `MorningQueryVariables`. Run it again whenever you change a query or download a new schema.

5. Call the API with the generated types:

   ```ts src/morning.ts theme={null}
   import { print } from 'graphql'
   import { MorningDocument, type MorningQuery, type MorningQueryVariables } from './gql/graphql'

   const API = (process.env.DARPAN_API ?? 'https://api.drpn.ai') + '/rest/s1/graphql/public'

   async function morning(variables: MorningQueryVariables): Promise<MorningQuery> {
     const res = await fetch(API, {
       method: 'POST',
       headers: { Authorization: `Bearer ${process.env.DARPAN_GQL_KEY}`, 'Content-Type': 'application/json' },
       body: JSON.stringify({ query: print(MorningDocument), variables }),
     })
     const body = await res.json()
     if (body.errors?.length) throw new Error(JSON.stringify(body.errors))
     return body.data as MorningQuery
   }

   morning({ audit: 'month-close' }).then((data) => {
     const health = data.auditReport?.health    // every field is nullable, so read with ?.
     console.log(health?.complete, health?.summary, data.auditReport?.summary?.open)
   })
   ```

   Run it with `npx tsx src/morning.ts`, or build it with your usual bundler. A misspelt field or a missing `$audit` now fails at generate or compile time, not in production.

## Pitfalls

| You see | Cause | Fix |
| - | - | - |
| `DateTime` and `Decimal` fields typed `any` | The generator does not know Darpan's custom scalars | Keep the `scalars` map. Both arrive as strings: parse a `Decimal` with a decimal library, not `Number`, to keep its precision |
| `Maybe<…>` on almost every field | Nearly every field in the schema is nullable | Read with `?.` and `??`, as in the example, and check `errors` before trusting a null |
| `Failed to find any GraphQL type definitions` | `schema:` points at `/graphql/sdl` directly. The endpoint returns JSON, not SDL | Download the file first with `jq -r .sdl`, and point `schema:` at it |
| `UNAUTHENTICATED` when the generator introspects | `schema:` points at `/graphql/public`, which needs a key for introspection | Use the downloaded file instead |

## Related

* [Common tasks](https://developers.drpn.ai/graphql/tasks.md): queries to start from
* [Versioning](https://developers.drpn.ai/graphql/versioning.md): how the schema changes over time
* [Errors](https://developers.drpn.ai/graphql/errors.md) and [Cost and throttling](https://developers.drpn.ai/graphql/cost-and-throttling.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.