The Codex API is authenticated using an API key. You can get your API key from the dashboard.

There are two types of API keys: secret, and short-lived.

Secret keys are long-lived and can be used to make requests to the API indefinitely. You must ensure that you don’t leak these to your users, as they can be used to make requests and incur costs.

Short-lived keys are good for when you need to allow untrusted parties like users to directly make requests to the Codex API. Maybe you have a website that provides the ability for users to subscribe to Codex websockets to get real-time updates for example.

You can generate as many short-lived keys as you want, and there are limits you can set on the expiration time & number of requests per key. See the details here

Api Key Example

For queries, you just add the Authorization header on every HTTP request to https://graph.codex.io/graphql and it will authorize you.

sdk.query(gql`
  query GetTokenPrices($inputs: [GetTokenPricesInput!]!) {
    getTokenPrices(inputs: $inputs) {
      priceUsd
      timestamp
      address
    }
  }
  `, {
  inputs: [{
    address: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c",
    networkId: 56
  }]
})

Short-Lived Key Example

Create a single short-lived key with a request limit of 1000 requests.

import { Codex } from "@codex-data/sdk"

const sdk = new Codex({ apiKey: "your-api-key" })

const { createApiTokens } = await sdk.mutation(gql`
  mutation CreateApiTokens($input: CreateApiTokensInput!) {
    createApiTokens(input: $input) {
      expiresTimeString
      id
      remaining
      requestLimit
      token
    }
  }
`, {
  input: {
    count: 1
    requestLimit: 1000
  }
})

const token = createApiTokens[0].token

// Now create a Codex instance with the short-lived key
const shortLivedCodex = new Codex({ apiKey: `Bearer ${token}` })

Then you can pass that token result as the apiKey when making further requests to the API, or subscribing with websockets.

One caveat is that the token is a JWT, so you must set the Authorization header to Bearer <token>. This is different from how secret keys work.

Errors

If you send an expired or invalid token, you will get a Unauthorized error like this.

Unauthorized
{
  "data": null,
  "errors": [
    {
      "message": "HTTP fetch failed from 'tokens': 401: Unauthorized",
      "path": [],
      "extensions": {
        "code": "SUBREQUEST_HTTP_ERROR",
        "service": "tokens",
        "reason": "401: Unauthorized",
        "http": {
          "status": 401
        }
      }
    },
    {
      "message": "Your API key was not found",
      "path": [],
      "extensions": {
        "code": "NOT_AUTHORIZED",
        "service": "tokens"
      }
    }
  ]
}