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

# Create an in-app survey session

> Decide whether to show an in-app survey to a signed-in person, and mint the signed embed URL if so. Call it from your backend, never from a browser: a request that carries an `Origin` header is refused with `403`, and cross-origin preflight requests are refused too. (Browser code uses a signed identity token with the in-app SDK instead. See the in-app SDK guide.) It returns `200` for both outcomes. When the person qualifies you get `eligible: true`, an `embedUrl` that is valid for one hour, a `sessionId` and the configured `delayMs`. Otherwise you get `eligible: false` and a `reason`: `disabled` (survey not active or in-app collection off), `cooldown`, `recently_dismissed`, `not_sampled`, `snoozed`, `already_seen`, `minimum_age`, `minimum_sessions`, `display_limit`, or, when the survey has targeting, `page_not_targeted`, `not_targeted` or `awaiting_trigger`. A survey with page rules needs `context.url`; without it the reason is `page_not_targeted`. A person who passes the earlier checks gets one recorded session per UTC day, and those count toward `minSessions`. `parentOrigin` must be listed in `settings.inApp.allowedOrigins`, or the call returns `403`. The person must exist, be active and belong to `accountId`, or the call returns `404`. Send `subject` to tie the survey to a deal, ticket, plan or custom record; a record GainTrace can't link returns `422`. Any invalid or malformed body, or an invalid survey id, returns `422`. Requires a secret server key (`gt_live_`). Publishable keys (`gt_pub_`) return `403`.

**Scope:** `write:surveys`



## OpenAPI

````yaml /openapi.json post /surveys/{id}/session
openapi: 3.1.0
info:
  title: GainTrace API
  version: 1.0.0
  description: >-
    The GainTrace REST API (v1). Read your customer data and push product-usage
    events, metric events, and signals into GainTrace.


    All endpoints are authenticated with a Bearer API key and scoped to a single
    workspace.


    Each API key can send 60 requests a minute. A `429` response includes a
    `Retry-After` header with the seconds to wait.
servers:
  - url: https://app.gaintrace.com/api/v1
    description: Production
security:
  - bearerAuth: []
tags:
  - name: Companies
    description: Read and manage canonical company records.
  - name: Signals
    description: Read, create, and manage buyer / risk signals.
  - name: Ingest
    description: Push product-usage and metric events into GainTrace.
  - name: Contacts
    description: >-
      The original path for People. It shares its handlers with /people, and
      also offers delete-by-key.
  - name: Webhooks
    description: Subscribe to workspace events with signed, retried delivery.
  - name: People
    description: Read and manage People. One Person can belong to many Companies.
  - name: NPS responses
    description: Import NPS scores from another survey tool and read your NPS history.
  - name: Surveys
    description: >-
      Create and launch surveys, request invitations, record responses and mint
      in-app sessions.
  - name: Survey responses
    description: Read the responses collected by your surveys.
  - name: Survey segments
    description: Save groups of Companies and People that surveys can target.
  - name: Survey imports
    description: Pull responses from the survey tools your workspace has connected.
paths:
  /surveys/{id}/session:
    post:
      tags:
        - Surveys
      summary: Create an in-app survey session
      description: >-
        Decide whether to show an in-app survey to a signed-in person, and mint
        the signed embed URL if so. Call it from your backend, never from a
        browser: a request that carries an `Origin` header is refused with
        `403`, and cross-origin preflight requests are refused too. (Browser
        code uses a signed identity token with the in-app SDK instead. See the
        in-app SDK guide.) It returns `200` for both outcomes. When the person
        qualifies you get `eligible: true`, an `embedUrl` that is valid for one
        hour, a `sessionId` and the configured `delayMs`. Otherwise you get
        `eligible: false` and a `reason`: `disabled` (survey not active or
        in-app collection off), `cooldown`, `recently_dismissed`, `not_sampled`,
        `snoozed`, `already_seen`, `minimum_age`, `minimum_sessions`,
        `display_limit`, or, when the survey has targeting, `page_not_targeted`,
        `not_targeted` or `awaiting_trigger`. A survey with page rules needs
        `context.url`; without it the reason is `page_not_targeted`. A person
        who passes the earlier checks gets one recorded session per UTC day, and
        those count toward `minSessions`. `parentOrigin` must be listed in
        `settings.inApp.allowedOrigins`, or the call returns `403`. The person
        must exist, be active and belong to `accountId`, or the call returns
        `404`. Send `subject` to tie the survey to a deal, ticket, plan or
        custom record; a record GainTrace can't link returns `422`. Any invalid
        or malformed body, or an invalid survey id, returns `422`. Requires a
        secret server key (`gt_live_`). Publishable keys (`gt_pub_`) return
        `403`.


        **Scope:** `write:surveys`
      operationId: createSurveySession
      parameters:
        - $ref: '#/components/parameters/surveyId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SurveySessionCreate'
            example:
              contactId: c3d24e5f-6a7b-4c8d-9e0f-1a2b3c4d5e6f
              accountId: a1f0c2d3-5e6f-4a7b-8c9d-0e1f2a3b4c5d
              parentOrigin: https://app.example.com
              mode: survey
      responses:
        '200':
          description: The session decision.
          content:
            application/json:
              schema:
                type: object
                required:
                  - data
                properties:
                  data:
                    $ref: '#/components/schemas/SurveySession'
              examples:
                eligible:
                  summary: Eligible
                  value:
                    data:
                      eligible: true
                      embedUrl: >-
                        https://app.gaintrace.com/survey/embed/7b6f2c1e-4d3a-4b5c-9e8f-1a2b3c4d5e6f?t=eyJ...&mode=survey&position=bottom
                      sessionId: b2c3d4e5-7a8b-4c9d-8e0f-2a3b4c5d6e7f
                      delayMs: 3000
                ineligible:
                  summary: Not eligible
                  value:
                    data:
                      eligible: false
                      reason: cooldown
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/InternalServerError'
        '503':
          $ref: '#/components/responses/ServiceUnavailable'
        '504':
          $ref: '#/components/responses/GatewayTimeout'
components:
  parameters:
    surveyId:
      name: id
      in: path
      required: true
      description: The survey's UUID.
      schema:
        type: string
        format: uuid
  schemas:
    SurveySessionCreate:
      type: object
      required:
        - contactId
        - accountId
        - parentOrigin
      additionalProperties: false
      description: >-
        Field names follow the code: `contactId` is a person id and `accountId`
        is a company id.
      properties:
        contactId:
          type: string
          format: uuid
          description: The signed-in person's id in GainTrace.
        accountId:
          type: string
          format: uuid
          description: The id of that person's company. It must match the person.
        parentOrigin:
          type: string
          format: uri
          maxLength: 255
          description: >-
            The exact origin of the page that will show the survey, such as
            `https://app.example.com`. It must be listed in the survey's
            `settings.inApp.allowedOrigins`.
        mode:
          type: string
          enum:
            - survey
            - test
          default: survey
          description: >-
            `test` skips eligibility rules and records nothing, so you can
            preview the survey.
        context:
          type: object
          required:
            - url
          additionalProperties: false
          description: >-
            What the person is doing right now. Send it when the survey has page
            rules or a trigger under `settings.inApp.targeting`.
          properties:
            url:
              type: string
              format: uri
              maxLength: 2048
              description: >-
                The page the person is on. It must be on `parentOrigin`, or the
                call returns `422`.
            event:
              type: string
              pattern: ^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$
              description: >-
                The event name your code sent with `GaintraceSurveys.track()`,
                for an `event` trigger.
            dwellSeconds:
              type: integer
              minimum: 0
              maximum: 86400
              description: Seconds on the page, for a `time_on_page` trigger.
        subject:
          $ref: '#/components/schemas/SurveySubjectInput'
          description: >-
            The deal, ticket, plan or custom record this survey asks about.
            Responses to the embed carry it as their `subject`. The record must
            belong to the same Company as the person. The record a response is
            about: a deal, ticket, plan or custom record. Name it by its
            GainTrace `id`, or, for a deal or ticket, by the id it has in your
            CRM or help desk (`externalId`, with `source` when more than one
            connection holds that id). For a custom record, send the data
            model's `model` slug and the record's `externalId`. The record must
            exist, must not be archived, and must belong to the same Company as
            the person.
        lang:
          type: string
          maxLength: 35
          description: >-
            A language tag such as `es` or `pt-BR`. The survey shows in this
            language when it has a translation for it. It wins over the person's
            `locale` or `language` trait and the browser.
    SurveySession:
      oneOf:
        - type: object
          required:
            - eligible
            - embedUrl
            - delayMs
          properties:
            eligible:
              type: boolean
              enum:
                - true
            embedUrl:
              type: string
              format: uri
              description: >-
                A signed URL that is valid for one hour. Pass it to
                `GaintraceSurveys.show`. It uses your verified custom domain
                while the white-label add-on is active.
            sessionId:
              type: string
              format: uuid
              description: Omitted in test mode.
            delayMs:
              type: integer
        - type: object
          required:
            - eligible
            - reason
          properties:
            eligible:
              type: boolean
              enum:
                - false
            reason:
              type: string
              enum:
                - disabled
                - cooldown
                - recently_dismissed
                - not_sampled
                - snoozed
                - already_seen
                - minimum_age
                - minimum_sessions
                - display_limit
                - page_not_targeted
                - not_targeted
                - awaiting_trigger
              description: >-
                Why the person doesn't see the survey now. `page_not_targeted`,
                `not_targeted` and `awaiting_trigger` come from the survey's
                targeting: the page didn't match, the person isn't in the
                audience, or the trigger hasn't fired yet. Ask again when the
                person reaches the page or fires the event.
            awaiting:
              type: object
              description: 'With `awaiting_trigger`: what the survey is waiting for.'
              properties:
                events:
                  type: array
                  items:
                    type: string
                timeOnPageSeconds:
                  type: integer
    SurveySubjectInput:
      description: >-
        The record a response is about: a deal, ticket, plan or custom record.
        Name it by its GainTrace `id`, or, for a deal or ticket, by the id it
        has in your CRM or help desk (`externalId`, with `source` when more than
        one connection holds that id). For a custom record, send the data
        model's `model` slug and the record's `externalId`. The record must
        exist, must not be archived, and must belong to the same Company as the
        person.
      oneOf:
        - type: object
          required:
            - type
            - id
          additionalProperties: false
          properties:
            type:
              type: string
              enum:
                - deal
                - ticket
                - plan
                - record
            id:
              type: string
              format: uuid
              description: The GainTrace record id.
        - type: object
          required:
            - type
            - externalId
          additionalProperties: false
          properties:
            type:
              type: string
              enum:
                - deal
                - ticket
            externalId:
              type: string
              maxLength: 255
              minLength: 1
            source:
              type: string
              minLength: 1
              maxLength: 64
              description: The connection the id comes from, such as `hubspot`. Lowercased.
        - type: object
          required:
            - type
            - model
            - externalId
          additionalProperties: false
          properties:
            type:
              type: string
              enum:
                - record
            model:
              type: string
              minLength: 1
              maxLength: 64
              description: The data model's slug.
            externalId:
              type: string
              maxLength: 255
              minLength: 1
    Error:
      type: object
      required:
        - error
      description: The standard error envelope. Every 4xx/5xx response uses this shape.
      properties:
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              enum:
                - bad_request
                - unauthorized
                - payment_required
                - forbidden
                - not_found
                - conflict
                - unprocessable_entity
                - rate_limit_exceeded
                - internal_server_error
                - service_unavailable
                - gateway_timeout
              description: >-
                Stable, machine-readable error code. Each code maps to exactly
                one HTTP status.
            message:
              type: string
              description: >-
                Human-readable, safe description of what went wrong. Never
                contains internal or provider detail.
            doc_url:
              type: string
              format: uri
              example: https://docs.gaintrace.com/errors#not_found
              description: Deep link to this code in the Errors reference.
  responses:
    Unauthorized:
      description: Missing, malformed, expired, or revoked API key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: unauthorized
              message: Missing Authorization header
              doc_url: https://docs.gaintrace.com/errors#unauthorized
    Forbidden:
      description: >-
        The key is valid but lacks the required scope, the origin is not
        allowed, or API v1 is not enabled for the workspace.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: forbidden
              message: 'Insufficient scope: write:companies required'
              doc_url: https://docs.gaintrace.com/errors#forbidden
    NotFound:
      description: >-
        The resource, or a resource you referenced, was not found in this
        workspace.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: not_found
              message: Company not found
              doc_url: https://docs.gaintrace.com/errors#not_found
    UnprocessableEntity:
      description: The request was well-formed but a value failed validation.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: unprocessable_entity
              message: 'Request validation failed. name: name is required'
              doc_url: https://docs.gaintrace.com/errors#unprocessable_entity
    RateLimited:
      description: >-
        The per-key rate limit was exceeded. Each API key can send 60 requests
        per minute, counted in calendar-minute windows. The `Retry-After` header
        gives the whole seconds (1 to 60) until the next window opens. Wait that
        long, then retry.
      headers:
        Retry-After:
          description: Whole seconds until the next one-minute window starts.
          schema:
            type: integer
            minimum: 1
            maximum: 60
          example: 23
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: rate_limit_exceeded
              message: >-
                Can't accept more than 60 requests a minute from one API key.
                Retry in 23 seconds.
              doc_url: https://docs.gaintrace.com/errors#rate_limit_exceeded
    InternalServerError:
      description: >-
        An unexpected error occurred on our side. The failure is logged; retry
        shortly.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: internal_server_error
              message: Something went wrong. Try again in a moment.
              doc_url: https://docs.gaintrace.com/errors#internal_server_error
    ServiceUnavailable:
      description: >-
        A backing service (for example, the database) was temporarily
        unavailable. Retry shortly.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: service_unavailable
              message: We had trouble reaching the database. Try again in a moment.
              doc_url: https://docs.gaintrace.com/errors#service_unavailable
    GatewayTimeout:
      description: >-
        The request took too long upstream before completing. Retry, and reduce
        batch size for large payloads.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: gateway_timeout
              message: The request timed out. Try again in a moment.
              doc_url: https://docs.gaintrace.com/errors#gateway_timeout
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        Bearer API key. Secret server keys start with `gt_live_`; client-safe
        browser keys start with `gt_pub_` (write-only, origin-pinned). Create
        and scope keys in Settings → API Keys.

````

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