openapi: 3.1.0

info:
  title: Tervan API
  version: 1.0.0
  description: |
    The server-to-server API for managing client references and advice sessions. Your backend calls it with a
    secret API key. The current public API covers creating, listing and retrieving clients and sessions, answering
    a session's questions, completing it with its outcome, and cancelling it. Browser embedding, document generation
    and webhook delivery are not exposed by this API.

    ## Conventions

    - **Authentication:** send your secret API key as a bearer token: `Authorization: Bearer tervan_sk_…`. Keep it
      on your servers; it must never reach a browser.
    - **IDs** are prefixed and opaque, for example `c_01j9zq3k8m2v7a5x6y4w3t2s1r` for a client. Store them as
      strings and don't parse them.
    - **Times** are RFC 3339, in UTC.
    - **Errors** are RFC 9457 problem details (`application/problem+json`). Tell problems apart by the status code,
      and by `type` for the few that have one; `detail` is for people and may change. When parts of the request are
      to blame, `errors` lists each one, with a JSON Pointer to a body field or the name of a parameter.
    - **Retries:** every `POST` accepts an `Idempotency-Key` header. A request repeated with the same key returns
      the first response instead of acting again, with the header `Idempotent-Replayed: true`. Reusing a key for a
      different request is an error. Only successful responses are stored, so a request that failed can be retried
      with the same key.
    - **Lists** are newest first and paginated with cursors. Pass a response's `next_cursor` as `cursor` to get the
      next page; it is `null` on the last page.
    - **Compatibility:** within `/v1`, changes are additive. New fields and new values in response enums can appear
      at any time, so ignore what you don't recognise. Unknown fields in requests are rejected.
  contact:
    name: Tervan
    url: https://tervan.io

servers:
  - url: https://api.tervan.io
    description: Contract base URL. Confirm access and the environment with Tervan before sending client data.

security:
  - apiKey: []

tags:
  - name: Clients
    description: |
      Account-scoped references to the people who receive advice. The client resource contains an optional
      external reference, an ID and a creation timestamp; it does not contain a personal profile.
  - name: Sessions
    description: |
      An advice session is one client working through one approved question-set version. Every answer is stored
      against that version, which never changes for the life of the session.
  - name: Questionnaire
    description: |
      A session's questions and answers. Which questions are shown depends on earlier answers, so the questionnaire
      can change after each answer.

paths:
  /v1/clients:
    post:
      operationId: createClient
      tags: [Clients]
      summary: Create a client
      description: Creates an account-scoped client reference. Send an empty object if you do not need an external reference.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateClientRequest"
      responses:
        "201":
          description: The new client.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Client"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          $ref: "#/components/responses/Conflict"
        "422":
          $ref: "#/components/responses/UnprocessableContent"
    get:
      operationId: listClients
      tags: [Clients]
      summary: List clients
      description: Returns clients in your account, newest first. An external_ref filter returns only a matching client.
      parameters:
        - name: external_ref
          in: query
          description: Only the client with this reference.
          schema:
            $ref: "#/components/schemas/ExternalRef"
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Cursor"
      responses:
        "200":
          description: A page of clients.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ClientList"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/clients/{client_id}:
    get:
      operationId: getClient
      tags: [Clients]
      summary: Get a client
      description: Retrieves a client in your account. An unknown ID, or an ID from another account, returns 404.
      parameters:
        - $ref: "#/components/parameters/ClientId"
      responses:
        "200":
          description: The client.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Client"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"

  /v1/sessions:
    post:
      operationId: createSession
      tags: [Sessions]
      summary: Start an advice session
      description: |
        Starts an open session for a client on an approved question-set version. Name the version exactly, as in
        `suitability-retail@4.2`, or give only the question set's key to use its latest approved version. The
        response shows the version the session is pinned to. The client and approved question-set version must
        already exist in your account. There is no public endpoint for publishing question sets.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateSessionRequest"
      responses:
        "201":
          description: The new session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Session"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "422":
          $ref: "#/components/responses/UnprocessableContent"
    get:
      operationId: listSessions
      tags: [Sessions]
      summary: List sessions
      description: Returns sessions in your account, newest first. Use client to limit the results to one client.
      parameters:
        - name: client
          in: query
          description: Only this client's sessions.
          schema:
            $ref: "#/components/schemas/ClientId"
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/Cursor"
      responses:
        "200":
          description: A page of sessions.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SessionList"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /v1/sessions/{session_id}:
    get:
      operationId: getSession
      tags: [Sessions]
      summary: Get a session
      description: Retrieves a session in your account. An unknown ID, or an ID from another account, returns 404.
      parameters:
        - $ref: "#/components/parameters/SessionId"
      responses:
        "200":
          description: The session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Session"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"

  /v1/sessions/{session_id}/cancel:
    post:
      operationId: cancelSession
      tags: [Sessions]
      summary: Cancel a session
      description: |
        Cancels an open session. It takes no more answers, and its retention period starts. Its answers are kept for
        the record. A session that's past its `expires_at` can't be cancelled: it has expired. A session that is
        no longer open, or has passed its expiry time, returns 409.
      parameters:
        - $ref: "#/components/parameters/SessionId"
        - $ref: "#/components/parameters/IdempotencyKey"
      responses:
        "200":
          description: The cancelled session.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Session"
              example:
                id: s_01j9zq4a7b6c5d4e3f2g1h0j9k
                client: c_01j9zq3k8m2v7a5x6y4w3t2s1r
                question_set: suitability-retail@4.2
                purpose: onboarding
                previous_session: null
                locale: nb-NO
                status: cancelled
                created_at: "2026-10-03T09:00:00Z"
                expires_at: "2026-11-02T09:00:00Z"
                completed_at: null
                answer_count: null
                answers_hash: null
                retain_until: "2033-10-03T10:00:00Z"
                outcome: null
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
        "422":
          $ref: "#/components/responses/UnprocessableContent"

  /v1/sessions/{session_id}/complete:
    post:
      operationId: completeSession
      tags: [Sessions]
      summary: Complete a session
      description: |
        Computes the outcome from the answers, records it with the answers and scores it was computed from, and
        completes the session. Its answers are locked: their count and hash are recorded, and nothing can be added.
        Every shown question that needs an answer must have one. A session with unanswered questions, a session
        that is no longer open, or one that has passed its expiry time returns 409.
      parameters:
        - $ref: "#/components/parameters/SessionId"
        - $ref: "#/components/parameters/IdempotencyKey"
      responses:
        "200":
          description: The completed session, with its outcome.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Session"
              example:
                id: s_01j9zq4a7b6c5d4e3f2g1h0j9k
                client: c_01j9zq3k8m2v7a5x6y4w3t2s1r
                question_set: suitability-retail@4.2
                purpose: onboarding
                previous_session: null
                locale: nb-NO
                status: completed
                created_at: "2026-10-03T09:00:00Z"
                expires_at: "2026-11-02T09:00:00Z"
                completed_at: "2026-10-03T09:12:00Z"
                answer_count: 7
                answers_hash: 93bef39411cdc8f47975275fa89394e73d13e255758e72ba0a0ffb23db48345c
                retain_until: "2033-10-03T09:12:00Z"
                outcome:
                  risk_level: 4
                  portfolio: balanced
                  sustainability_preferences: true
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
        "422":
          $ref: "#/components/responses/UnprocessableContent"

  /v1/sessions/{session_id}/questionnaire:
    get:
      operationId: getQuestionnaire
      tags: [Questionnaire]
      summary: Get a session's questions
      description: |
        Returns the questions the client sees now, in order and in the session's locale, with the current answer to
        each. A question can be shown or hidden by earlier answers, so fetch the questionnaire again after answering.
      parameters:
        - $ref: "#/components/parameters/SessionId"
      responses:
        "200":
          description: The questionnaire.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Questionnaire"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"

  /v1/sessions/{session_id}/answers:
    post:
      operationId: submitAnswers
      tags: [Questionnaire]
      summary: Answer questions
      description: |
        Records answers given through your system. They are checked in order, each against the questions shown after
        the answers before it, and saved together or not at all. Answering a question again records a correction:
        the earlier answer stays on record, replaced by the new one. An answer equal to the current one changes
        nothing. A session that is no longer open, or has passed its expiry time, returns 409; an answer that doesn't
        fit its question returns 422, with a pointer to it.
      parameters:
        - $ref: "#/components/parameters/SessionId"
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SubmitAnswersRequest"
      responses:
        "200":
          description: The questionnaire, after the answers.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Questionnaire"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
        "422":
          $ref: "#/components/responses/UnprocessableContent"

components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      description: A secret API key beginning with `tervan_sk_`. Arrange credentials with Tervan; there is no public key-management endpoint or dashboard provisioning flow in this API. Keep the key on your server.

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      description: |
        Makes the request safe to retry. Use a new random value, such as a UUID, for each distinct request. Keys are
        scoped to your account.
      schema:
        type: string
        minLength: 1
        maxLength: 255
    Limit:
      name: limit
      in: query
      description: The most items to return.
      schema:
        type: integer
        format: int32
        minimum: 1
        maximum: 100
        default: 20
    Cursor:
      name: cursor
      in: query
      description: The `next_cursor` of the previous page.
      schema:
        type: string
        minLength: 1
        maxLength: 255
    ClientId:
      name: client_id
      in: path
      required: true
      schema:
        $ref: "#/components/schemas/ClientId"
    SessionId:
      name: session_id
      in: path
      required: true
      schema:
        $ref: "#/components/schemas/SessionId"

  responses:
    BadRequest:
      description: The request is malformed or fails validation.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
    Unauthorized:
      description: The API key is missing, unknown or revoked.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
    NotFound:
      description: Nothing with this ID exists in your account.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
    Conflict:
      description: The request conflicts with the current state, for example a reference that's already in use.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
    UnprocessableContent:
      description: |
        The request is well formed but can't be carried out, for example because it refers to something that
        doesn't exist, or reuses an idempotency key for a different request.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"

  schemas:
    ClientId:
      type: string
      description: A client ID, starting with `c_`.
      pattern: "^c_[0-7][0-9a-hjkmnp-tv-z]{25}$"
      examples: [c_01j9zq3k8m2v7a5x6y4w3t2s1r]
    SessionId:
      type: string
      description: A session ID, starting with `s_`.
      pattern: "^s_[0-7][0-9a-hjkmnp-tv-z]{25}$"
      examples: [s_01j9zq4a7b6c5d4e3f2g1h0j9k]
    ExternalRef:
      type: string
      description: Your own ID for the client, such as its ID in your CRM. Unique within your account.
      minLength: 1
      maxLength: 255
      examples: [crm-104233]

    CreateClientRequest:
      type: object
      additionalProperties: false
      examples:
        - external_ref: crm-104233
      properties:
        external_ref:
          $ref: "#/components/schemas/ExternalRef"

    Client:
      type: object
      required: [id, external_ref, created_at]
      examples:
        - id: c_01j9zq3k8m2v7a5x6y4w3t2s1r
          external_ref: crm-104233
          created_at: "2026-10-03T09:00:00Z"
      properties:
        id:
          $ref: "#/components/schemas/ClientId"
        external_ref:
          type: [string, "null"]
          description: Your own ID for the client, if you gave one.
        created_at:
          type: string
          format: date-time
          examples: ["2026-10-03T09:00:00Z"]

    ClientList:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items:
            $ref: "#/components/schemas/Client"
        next_cursor:
          type: [string, "null"]
          description: Pass as `cursor` to get the next page. `null` on the last page.

    SessionPurpose:
      type: string
      description: |
        Why the session was started.
        - `onboarding`: the first assessment, when the client relationship starts.
        - `periodic_review`: the periodic suitability review, usually annual.
      enum: [onboarding, periodic_review]

    SessionStatus:
      type: string
      description: |
        - `open`: taking answers.
        - `completed`: finished. Its answers are locked: their count and hash are recorded, and nothing can be added.
        - `cancelled`: stopped before it was completed.
        - `expired`: not completed before `expires_at`. A session takes no more answers once `expires_at` has
          passed, and is marked expired within about a minute.
      enum: [open, completed, cancelled, expired]

    CreateSessionRequest:
      type: object
      additionalProperties: false
      required: [client, question_set, purpose, locale]
      examples:
        - client: c_01j9zq3k8m2v7a5x6y4w3t2s1r
          question_set: suitability-retail@4.2
          purpose: onboarding
          locale: nb-NO
      properties:
        client:
          $ref: "#/components/schemas/ClientId"
        question_set:
          type: string
          description: |
            The question set's key, such as `suitability-retail`, for its latest approved version, or a key and
            version, such as `suitability-retail@4.2`, for that exact version.
          pattern: "^[a-z0-9]+(-[a-z0-9]+)*(@(0|[1-9][0-9]{0,8})\\.(0|[1-9][0-9]{0,8}))?$"
          examples: [suitability-retail@4.2]
        purpose:
          $ref: "#/components/schemas/SessionPurpose"
        previous_session:
          $ref: "#/components/schemas/SessionId"
          description: |
            Only for a periodic review: a completed session belonging to this same client. A missing session,
            another client's session, an incomplete session or use with onboarding returns 422.
        locale:
          type: string
          description: The language the questions are shown in. One of the locales the question-set version is written in.
          pattern: "^[a-z]{2}-[A-Z]{2}$"
          examples: [nb-NO]
        expires_at:
          type: string
          format: date-time
          description: |
            When the session expires if it hasn't been completed. It takes no answers after that. In the future; 30 days
            from now by default.

    Session:
      type: object
      examples:
        - id: s_01j9zq4a7b6c5d4e3f2g1h0j9k
          client: c_01j9zq3k8m2v7a5x6y4w3t2s1r
          question_set: suitability-retail@4.2
          purpose: onboarding
          previous_session: null
          locale: nb-NO
          status: open
          created_at: "2026-10-03T09:00:00Z"
          expires_at: "2026-11-02T09:00:00Z"
          completed_at: null
          answer_count: null
          answers_hash: null
          retain_until: null
          outcome: null
      required:
        - id
        - client
        - question_set
        - purpose
        - previous_session
        - locale
        - status
        - created_at
        - expires_at
        - completed_at
        - answer_count
        - answers_hash
        - retain_until
        - outcome
      properties:
        id:
          $ref: "#/components/schemas/SessionId"
        client:
          $ref: "#/components/schemas/ClientId"
        question_set:
          type: string
          description: The question-set version the session is pinned to, as key@major.minor.
          examples: [suitability-retail@4.2]
        purpose:
          $ref: "#/components/schemas/SessionPurpose"
        previous_session:
          type: [string, "null"]
          description: For a periodic review, the session it follows on from.
        locale:
          type: string
        status:
          $ref: "#/components/schemas/SessionStatus"
        created_at:
          type: string
          format: date-time
        expires_at:
          type: string
          format: date-time
          examples: ["2026-11-02T09:00:00Z"]
        completed_at:
          type: [string, "null"]
          format: date-time
        answer_count:
          type: [integer, "null"]
          format: int32
          description: Once completed, how many answers the session holds, corrections included.
        answers_hash:
          type: [string, "null"]
          description: |
            Once completed, the SHA-256 of the session's answers in lowercase hex. This API does not expose an
            answer export endpoint.
        retain_until:
          type: [string, "null"]
          format: date-time
          description: |
            Once the session is completed, cancelled or expired, the earliest time its record may be deleted. It can be
            extended, never shortened.
        outcome:
          type: [object, "null"]
          additionalProperties: true
          description: |
            Once completed, the outcome computed from the answers, such as a risk level. The question set defines its
            fields. A field is `null` when it rests on a question that wasn't answered.

    SessionList:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items:
            $ref: "#/components/schemas/Session"
        next_cursor:
          type: [string, "null"]
          description: Pass as `cursor` to get the next page. `null` on the last page.

    Problem:
      type: object
      description: An RFC 9457 problem details object.
      required: [title, status]
      examples:
        - type: about:blank
          title: Bad Request
          status: 400
          detail: The request isn't valid. Each problem is listed in errors.
          instance: /v1/clients
          errors:
            - detail: Unknown field.
              pointer: "#/externalRef"
      properties:
        type:
          type: string
          format: uri
          description: |
            Identifies the kind of problem, for the few that need more than the status code, for example
            `https://docs.tervan.io/problems/idempotency-key-reused`. Left out when the status code says it all, which
            means `about:blank`.
        title:
          type: string
          description: A short summary of the kind of problem.
        status:
          type: integer
          format: int32
        detail:
          type: string
          description: What went wrong with this request, for people to read.
        instance:
          type: string
          description: The request path.
        errors:
          type: array
          description: Each part of the request that caused the problem.
          items:
            $ref: "#/components/schemas/ValidationError"

    Questionnaire:
      type: object
      required: [session, locale, questions, unanswered, ready_to_complete]
      examples:
        - session: s_01j9zq4a7b6c5d4e3f2g1h0j9k
          locale: en-GB
          questions:
            - key: horizon
              type: single_choice
              text: How long do you plan to keep this money invested?
              help: null
              required: true
              options:
                - value: short
                  label: Under 3 years
                - value: long
                  label: 10 years or more
              min_selected: null
              max_selected: null
              min: null
              max: null
              integer: false
              unit: null
              max_length: null
              answer: long
          unanswered: []
          ready_to_complete: true
      properties:
        session:
          $ref: "#/components/schemas/SessionId"
        locale:
          type: string
          description: The locale the texts are in.
        questions:
          type: array
          description: The questions shown now, in order.
          items:
            $ref: "#/components/schemas/QuestionnaireQuestion"
        unanswered:
          type: array
          description: The keys of shown questions that still need an answer.
          items:
            type: string
        ready_to_complete:
          type: boolean
          description: Whether the session can be completed now.

    QuestionnaireQuestion:
      type: object
      description: |
        A question as the client sees it. The fields after `options` say what makes a valid answer; they are `null`
        when they don't apply to the question's type.
      required:
        - key
        - type
        - text
        - help
        - required
        - options
        - min_selected
        - max_selected
        - min
        - max
        - integer
        - unit
        - max_length
        - answer
      properties:
        key:
          type: string
          description: Identifies the question. Use it when answering.
        type:
          type: string
          description: |
            How the question is answered, and so what the answer is:
            - `single_choice`: one option's value.
            - `multiple_choice`: a list of option values.
            - `number`: a number, with at most 15 significant digits and 6 decimal places.
            - `yes_no`: `true` or `false`.
            - `text`: text.
          enum: [single_choice, multiple_choice, number, yes_no, text]
        text:
          type: string
        help:
          type: [string, "null"]
          description: Further explanation to show with the question.
        required:
          type: boolean
          description: Whether the session needs an answer to the question before it can be completed.
        options:
          type: array
          description: The options of a choice question, in order. Empty for other types.
          items:
            $ref: "#/components/schemas/QuestionOption"
        min_selected:
          type: [integer, "null"]
          format: int32
        max_selected:
          type: [integer, "null"]
          format: int32
        min:
          type: [number, "null"]
        max:
          type: [number, "null"]
        integer:
          type: boolean
          description: Whether a number must be a whole number.
        unit:
          type: [string, "null"]
          description: The unit of a number, such as NOK.
        max_length:
          type: [integer, "null"]
          format: int32
          description: The most characters a text answer can have.
        answer:
          description: The current answer, in the form its type describes, or `null` when there is none.
          examples: [long]

    QuestionOption:
      type: object
      required: [value, label]
      properties:
        value:
          type: string
          description: What an answer gives to choose this option.
        label:
          type: string

    SubmitAnswersRequest:
      type: object
      additionalProperties: false
      required: [answers]
      examples:
        - answers:
            - question: horizon
              value: long
            - question: amount
              value: 500000
      properties:
        answers:
          type: array
          description: At least one answer, applied in order.
          items:
            $ref: "#/components/schemas/AnswerInput"

    AnswerInput:
      type: object
      additionalProperties: false
      required: [question, value]
      properties:
        question:
          type: string
          description: The question's key.
          pattern: "^[a-z][a-z0-9_]{0,63}$"
          examples: [horizon]
        value:
          description: The answer, in the form the question's type describes.
          examples: [long]

    ValidationError:
      type: object
      description: One part of a request that's invalid. It has either a `pointer` or a `parameter`.
      required: [detail]
      properties:
        detail:
          type: string
          description: What's wrong with it, for people to read.
        pointer:
          type: string
          description: A JSON Pointer to the field in the request body, in URI fragment form (RFC 6901).
          examples: ["#/external_ref"]
        parameter:
          type: string
          description: The name of the query, path or header parameter.
          examples: [limit]
