API guide · independent demonstration

The Library API: A GraphQL Guide

Queries, variables, pagination, a mutation and two kinds of errors, with every example tested against the API on each build.

The library API is a small GraphQL API over the documents of this portfolio's library. You read documents with queries, a page at a time, and send feedback on a document with a mutation.

I built the API to write its documentation: it runs on your own computer, keeps feedback in memory only, and isn't connected to any company's service. Every request and response on this page is real. A script sends each one to a fresh server on every build of this site, and the build fails if an answer changes.

Before You Start#

You need Node.js 22 and Git.

  1. Get the code and install it:

    git clone https://github.com/domail2karandeshmukh-cyber/portfolio.git
    cd portfolio
    npm install
  2. Start the server:

    node content/work/graphql/server.mjs

    It answers at http://localhost:4000/graphql. To use another port, set PORT. To change the access token, set LIBRARY_API_TOKEN; it's local-demo-token otherwise.

Send Your First Query#

Every request is an HTTP POST to /graphql, with a JSON body that holds the query and, when it has any, its variables.

Example: Read the first page of documents

curl -s http://localhost:4000/graphql \
  -H 'Content-Type: application/json' \
  -d '{"query":"query FirstPage {\n  documents(first: 3) {\n    totalCount\n    edges {\n      cursor\n      node { id title kind }\n    }\n    pageInfo { hasNextPage endCursor }\n  }\n}"}'

Response, HTTP 200:

{
  "data": {
    "documents": {
      "totalCount": 25,
      "edges": [
        {
          "cursor": "ZG9jOjA=",
          "node": {
            "id": "cg-threat",
            "title": "Threat model",
            "kind": "SECURITY"
          }
        },
        {
          "cursor": "ZG9jOjE=",
          "node": {
            "id": "tn-demo",
            "title": "The demonstration in two minutes",
            "kind": "HOW_TO"
          }
        },
        {
          "cursor": "ZG9jOjI=",
          "node": {
            "id": "tn-how",
            "title": "How TrustNav works, step by step",
            "kind": "CONCEPT"
          }
        }
      ],
      "pageInfo": {
        "hasNextPage": true,
        "endCursor": "ZG9jOjI="
      }
    }
  }
}

The answer has the shape of the query: the fields you asked for, and nothing else.

Authentication#

Queries need no token. The mutation, submitFeedback, needs an access token in an Authorization header:

Authorization: Bearer local-demo-token

Without it, the server refuses the mutation with a GraphQL error whose code is UNAUTHENTICATED:

Example: Send feedback without a token

mutation SendFeedback($input: SubmitFeedbackInput!) {
  submitFeedback(input: $input) {
    __typename
  }
}

Variables:

{
  "input": {
    "documentId": "kc-reset-otp",
    "helpful": true
  }
}

Response, HTTP 200:

{
  "errors": [
    {
      "message": "Send an access token: Authorization: Bearer <token>.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "submitFeedback"
      ],
      "extensions": {
        "code": "UNAUTHENTICATED"
      }
    }
  ],
  "data": null
}

The Schema#

The whole schema is in schema.graphql, with a description on each type and field. The types you'll use most:

Type What it is
Document A document of the library: id, title, kind, project and url.
DocumentKind What a document is for: HOW_TO, CONCEPT, REFERENCE, TROUBLESHOOTING and five more.
DocumentConnection A page of documents: edges, pageInfo and totalCount.
SubmitFeedbackPayload What the mutation returns: the feedback, or the problem that stopped it.

The server answers introspection queries, so a GraphQL client such as GraphiQL or Postman can read the schema from it.

Use Variables#

Put the values that change in variables, and keep the query the same. Declare each variable with its type after the operation's name, use it with $, and send its value in variables:

Example: Read one document

query OneDocument($id: ID!) {
  document(id: $id) { title kind project url }
}

Variables:

{
  "id": "kc-reset-otp"
}

Response, HTTP 200:

{
  "data": {
    "document": {
      "title": "Reset a user's OTP credential in Keycloak",
      "kind": "HOW_TO",
      "project": "Keycloak (independent)",
      "url": "https://karandeshmukh.dev/docs/keycloak/reset-otp"
    }
  }
}

A document that doesn't exist isn't an error: document is null.

Example: Ask for a document that doesn't exist

query OneDocument($id: ID!) {
  document(id: $id) { title }
}

Variables:

{
  "id": "kc-reset-2fa"
}

Response, HTTP 200:

{
  "data": {
    "document": null
  }
}

Read Page by Page#

documents returns a connection, in the shape of the GraphQL Cursor Connections Specification:

  • edges holds the page's documents. Each edge has the document, node, and a cursor that marks its place.
  • pageInfo says whether there's a page after this one, hasNextPage, and gives the cursor of the page's last document, endCursor.
  • totalCount is the number of documents that match, the same on every page.
  • first sets the size of a page: from 1 to 50, and 10 if you leave it out.

To read the next page, send the endCursor of the last page as after. Stop when hasNextPage is false.

Example: Read the next page

query NextPage($after: String) {
  documents(first: 3, after: $after) {
    edges { node { id title } }
    pageInfo { hasPreviousPage hasNextPage endCursor }
  }
}

Variables:

{
  "after": "ZG9jOjI="
}

Response, HTTP 200:

{
  "data": {
    "documents": {
      "edges": [
        {
          "node": {
            "id": "studio-shots-guide",
            "title": "Annotate a screenshot in the Screenshot Studio"
          }
        },
        {
          "node": {
            "id": "kc1-model-card",
            "title": "Model card: KC1 defect prediction"
          }
        },
        {
          "node": {
            "id": "kc1-dataset-card",
            "title": "Dataset card: NASA PROMISE KC1, as the KC1 project uses it"
          }
        }
      ],
      "pageInfo": {
        "hasPreviousPage": true,
        "hasNextPage": true,
        "endCursor": "ZG9jOjU="
      }
    }
  }
}

A cursor is opaque: use it as the API gives it. Don't build one, and don't store one for later, because it marks a place in today's list.

Keep One Kind of Document#

kind keeps only the documents of one kind. totalCount counts those only.

Example: Keep one kind of document

query HowTos {
  documents(kind: HOW_TO, first: 50) {
    totalCount
    edges { node { title project } }
  }
}

Response, HTTP 200:

{
  "data": {
    "documents": {
      "totalCount": 8,
      "edges": [
        {
          "node": {
            "title": "The demonstration in two minutes",
            "project": "TrustNav"
          }
        },
        {
          "node": {
            "title": "Annotate a screenshot in the Screenshot Studio",
            "project": "Documentation Studio"
          }
        },
        {
          "node": {
            "title": "Manual Docker build guide",
            "project": "KC1 defect prediction"
          }
        },
        {
          "node": {
            "title": "Get your first prediction from the KC1 API",
            "project": "KC1 defect prediction"
          }
        },
        {
          "node": {
            "title": "Compare the KC1 model candidates in MLflow",
            "project": "KC1 defect prediction"
          }
        },
        {
          "node": {
            "title": "Reset a user's OTP credential in Keycloak",
            "project": "Keycloak (independent)"
          }
        },
        {
          "node": {
            "title": "Run a notebook from a clean start and share it as HTML in JupyterLab",
            "project": "JupyterLab (independent)"
          }
        },
        {
          "node": {
            "title": "Find the slowest HTTP responses in a capture with tshark",
            "project": "Wireshark (independent)"
          }
        }
      ]
    }
  }
}

Send Feedback#

submitFeedback records a reader's answer to "Did this help?", with an optional comment of up to 500 characters.

Example: Send feedback

mutation SendFeedback($input: SubmitFeedbackInput!) {
  submitFeedback(input: $input) {
    __typename
    ... on SubmitFeedbackSuccess {
      feedback { id documentId helpful comment }
    }
    ... on Problem { message }
  }
}

Variables:

{
  "input": {
    "documentId": "kc-reset-otp",
    "helpful": false,
    "comment": "Step 5 doesn't say what to do if the user has other required actions."
  }
}

With the header Authorization: Bearer local-demo-token.

Response, HTTP 200:

{
  "data": {
    "submitFeedback": {
      "__typename": "SubmitFeedbackSuccess",
      "feedback": {
        "id": "fb-1",
        "documentId": "kc-reset-otp",
        "helpful": false,
        "comment": "Step 5 doesn't say what to do if the user has other required actions."
      }
    }
  }
}

Ask for __typename and use fragments, ... on SubmitFeedbackSuccess, because the mutation returns one of three types: the next section says why.

Errors and Problems#

The API reports two kinds of failure, in two places.

GraphQL errors are in the response's errors list, and data is null for the field that failed. They mean the request itself is wrong: a missing token, an argument out of range, a field that doesn't exist. Each error has a message, and most have a code in extensions.

extensions.code Cause What to do
UNAUTHENTICATED The mutation was sent without a valid token. Send Authorization: Bearer <token>.
BAD_USER_INPUT An argument is out of range: first above 50, or a cursor the API didn't give. extensions.argument names it. Change the argument.
(none) The query doesn't match the schema: GraphQL rejects it before it runs. Check the field's name and type in the schema.

Example: Ask for a page that is too large

query {
  documents(first: 100) { totalCount }
}

Response, HTTP 200:

{
  "errors": [
    {
      "message": "`first` must be between 1 and 50.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "documents"
      ],
      "extensions": {
        "code": "BAD_USER_INPUT",
        "argument": "first"
      }
    }
  ],
  "data": null
}

Example: Ask for a field that doesn't exist

query {
  document(id: "kc-reset-otp") { title author }
}

Response, HTTP 200:

{
  "errors": [
    {
      "message": "Cannot query field \"author\" on type \"Document\".",
      "locations": [
        {
          "line": 2,
          "column": 40
        }
      ]
    }
  ]
}

Problems are part of the mutation's answer, in data. They mean the request was valid, but a rule of the API stopped it. Each problem is a type of its own that implements Problem, so a client can handle each one by its type and still read message from any of them.

Type Cause Extra field
DocumentNotFoundProblem No document has the documentId you sent. documentId
CommentTooLongProblem The comment is longer than 500 characters. maxLength

Example: Send feedback on a document that doesn't exist

mutation SendFeedback($input: SubmitFeedbackInput!) {
  submitFeedback(input: $input) {
    __typename
    ... on Problem { message }
    ... on DocumentNotFoundProblem { documentId }
  }
}

Variables:

{
  "input": {
    "documentId": "kc-reset-2fa",
    "helpful": true
  }
}

With the header Authorization: Bearer local-demo-token.

Response, HTTP 200:

{
  "data": {
    "submitFeedback": {
      "__typename": "DocumentNotFoundProblem",
      "message": "No document has this ID.",
      "documentId": "kc-reset-2fa"
    }
  }
}

Example: Send a comment that is too long

mutation SendFeedback($input: SubmitFeedbackInput!) {
  submitFeedback(input: $input) {
    __typename
    ... on Problem { message }
    ... on CommentTooLongProblem { maxLength }
  }
}

Variables:

{
  "input": {
    "documentId": "kc-reset-otp",
    "helpful": false,
    "comment": "xxxxxxxxxxxxxxxxxxxxxxxx… (501 characters)"
  }
}

With the header Authorization: Bearer local-demo-token.

Response, HTTP 200:

{
  "data": {
    "submitFeedback": {
      "__typename": "CommentTooLongProblem",
      "message": "The comment is longer than 500 characters.",
      "maxLength": 500
    }
  }
}

Troubleshooting#

What you see Cause Fix
Connection refused The server isn't running, or runs on another port. Start it with node content/work/graphql/server.mjs, and check PORT.
HTTP 405 The request was a GET. Send a POST.
HTTP 400 and The request body isn't valid JSON. The body isn't JSON: often a quote left unescaped in the shell. Put the body in a file and send it with curl -d @request.json.
UNAUTHENTICATED on the mutation No token, or a token that doesn't match LIBRARY_API_TOKEN. Send the token the server was started with.
The same first page each time after wasn't sent, or was sent outside variables. Send the last page's endCursor as after.
data is null and there's no errors You asked for document with an ID that doesn't exist. Read the IDs from documents first.

How the Examples Are Tested#

examples.json holds every request on this page and the response it got. On each build of the site, scripts/graphql-examples.mjs starts a fresh server, sends the requests in order and compares each answer, byte for byte. If the API changes an answer, the build stops until this page shows the new one.