Skip to content
LogoLogo

How to read project data from an app

This guide shows you how to call the Picked GraphQL API from the server of your app, for the project of one installation. The example reads the newest leads of the project.

You need an app with a server that uses @picked/app-kit, and the private key of the app. Build and install your first app makes these.

1. Ask for the scopes

Add each scope that your queries need to scopes in the manifest. To read leads, ask for organization_leads/read:

picked.config.ts
import { defineConfig } from '@picked/config/define'
 
const endpoint = process.env.APP_PUBLIC_URL ?? 'http://localhost:4103'
 
export default defineConfig({
  app: {
    handle: 'lead-insights',
    name: 'Lead Insights',
    endpoint,
    scopes: ['organization_leads/read'],
    slots: [{ location: 'app-home', url: `${endpoint}/`, title: 'Recent leads', height: 320 }],
  },
})

The person who installs the app sees these scopes and accepts them. That person must hold each scope on the project. Each token of the installation carries the accepted scopes, and no other scope. Scopes tells which names are valid.

When you add a scope to an app that is installed, deploy a new version. Each installation keeps the scopes of its old version until a person upgrades it and accepts the new scope. Refer to Upgrade an app.

2. Write the query

Write the GraphQL operation with graphql from @picked/admin-api-client. Install the package in the app directory first:

npm install @picked/admin-api-client

graphql makes a typed document from the operation. Use the projectId of the request, not an ID from the page:

src/leads.ts
import { graphql, type ResultOf } from '@picked/admin-api-client'
import { installationClientFor, type InstallationRef } from '@picked/app-kit/server'
 
const RecentLeadsDocument = graphql(`
  query RecentLeads($projectId: ID!, $first: Int!) {
    project(input: { id: $projectId }) {
      leads(first: $first) {
        matchCount
        nodes {
          id
          createdAt
        }
      }
    }
  }
`)
 
export async function recentLeads(
  privateKey: string,
  installation: InstallationRef,
  sessionToken?: string | null,
): Promise<ResultOf<typeof RecentLeadsDocument>> {
  const client = installationClientFor(installation, { privateKey, sessionToken })
  return client.request(RecentLeadsDocument, { projectId: installation.projectId, first: 10 })
}

client.request sends the operation to <apiUrl>/api/graphql with a token of the installation. It returns data, with the type of the document. If the answer has errors, it throws an AdminApiResponseError. The message of this error has the message of each error, and its codes has the code of each error. A query outside the scopes of the installation fails. A request that takes more than 30 seconds stops with an error.

The Management API lists each operation and the scope that it needs.

3. Call the API from a request from Picked

A lifecycle event, an app event, a tool call and an MCP request each contain a token. The token is valid for one hour and carries the scopes of the installation. Give the request to installationClientFor, and the client uses that token:

src/server.ts
import { createAppHandler, readAppEnvironment } from '@picked/app-kit/server'
import { serve } from '@picked/app-kit/node'
import { recentLeads } from './leads'
 
const port = process.env.APP_PORT ?? '4103'
const { privateKey, pickedKeys } = readAppEnvironment(process.env, port)
 
const handler = createAppHandler({
  pickedKeys,
  async onInstall(event) {
    console.log(await recentLeads(privateKey, event))
  },
})
 
serve(handler, Number(port))

4. Call the API from a page request

A request from a page of your app does not come from Picked, so it contains no token. It contains the session token of the person, in the Authorization header. Verify the session with readSession. Then give the raw session token to the client with sessionTokenOf:

src/server.ts
import { json, readSession, sessionTokenOf } from '@picked/app-kit/server'
 
// In the `fallback` of `createAppHandler`:
if (pathname === '/api/leads') {
  const session = await readSession(request, pickedKeys)
  if (session === null) return json({ error: 'unauthenticated' }, 401)
  try {
    return json(await recentLeads(privateKey, session, sessionTokenOf(request)))
  } catch (error) {
    return json({ error: error instanceof Error ? error.message : String(error) }, 502)
  }
}

The client sends appInstallationTokenCreate with the session token. Picked then gives a token for the installation. The client signs the request with the private key of the app.

The page sends the session token from connect():

import { connect } from '/app-kit/frame.js'
 
const context = await connect()
const response = await fetch('/api/leads', {
  headers: { authorization: `Bearer ${context.sessionToken}` },
})

A session token expires 10 minutes after Picked makes it. On a page that stays open, use keepConnected, which gets a new token before the old token expires. How to add a page to the dashboard shows the full page.

5. Call the API outside a request

To call Picked when no request comes in, for example at an interval that you set, set offlineAccess: true in the manifest:

picked.config.ts
export default defineConfig({
  app: {
    handle: 'lead-insights',
    name: 'Lead Insights',
    endpoint,
    scopes: ['organization_leads/read'],
    offlineAccess: true,
  },
})

The person who installs or upgrades the app accepts this access in the consent window.

Keep the installationId and apiUrl of each installation, for example from the installation.created event. Then make a client without a token:

src/sync.ts
import { graphql } from '@picked/admin-api-client'
import { createInstallationClient } from '@picked/app-kit/server'
 
const LeadCountDocument = graphql(`
  query LeadCount($id: ID!) {
    project(input: { id: $id }) {
      leads(first: 1) {
        matchCount
      }
    }
  }
`)
 
const client = createInstallationClient({
  apiUrl: 'https://api.picked.app',
  installationId: 'appi_k3v9x2m1q8zt',
  privateKey: process.env.PICKED_APP_PRIVATE_KEY ?? '',
})
 
const data = await client.request(LeadCountDocument, { id: 'proj_4kd9a2' })

The client gets a token with appInstallationTokenCreate at any time. It gets a new token 60 seconds before the old token expires.

Without offlineAccess, Picked refuses that request. The appInstallationTokenCreate mutation gives the error message.

6. Know when a token stops

A token of the installation stops in these conditions:

  • One hour after Picked makes it.
  • When a person removes the app from the project.