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

# Seed Form Filling Session Context

> Seed Form filling session context for a Form filling session using the Form filling URL binding

Use this endpoint to provide (seed) the
<Tooltip tip="Metadata provided when creating an ambient session that helps guide note generation and improve output quality." cta="View in Glossary" href="/Glossary/s">session context</Tooltip> for Form filling sessions. Providing detailed context helps Suki generate a more accurate and relevant <Tooltip tip="The final structured medical documentation generated from a patient encounter, organized into standardized sections using LOINC codes." cta="View in Glossary" href="/Glossary/c">clinical note</Tooltip>.

<Note>
  The body of this request is optional. However, if you decide to provide context, you must provide **valid values** for the properties.
</Note>

## Code examples

<Note>
  The code examples below use placeholders and the stage host `sdp.suki-stage.com` only as **examples**.
  For credentials, base URLs, where to run Python or TypeScript, CORS, and **cURL**, refer to [Using code examples in your integration](/api-reference/api-guidelines#using-code-examples-in-your-integration) in the **API Reference Guidelines**.
</Note>

<Tabs>
  <Tab title="Python">
    ```python expandable theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
    from typing import Any, Optional, TypedDict

    import requests

    BASE_URL = "https://sdp.suki-stage.com"


    class FormFillingMetadata(TypedDict):
        form_template_id: str


    class FormFillingContext(TypedDict):
        values: list[FormFillingMetadata]


    class FormFillingSessionContext(TypedDict, total=False):
        # Optional, but if provided, `values` and `form_template_id` are required.
        form_filling: FormFillingContext


    class ApiHttpError(RuntimeError):
        def __init__(self, status: int, url: str, detail: str) -> None:
            super().__init__(f"HTTP {status} {url}: {detail}")
            self.status = status
            self.url = url


    def _post_json_expect(
        url: str,
        headers: dict[str, str],
        payload: dict[str, Any],
        expect_status: int,
    ) -> Optional[dict[str, Any]]:
        r = requests.post(url, json=payload, headers=headers, timeout=60)
        if r.status_code == expect_status:
            # OpenAPI does not define a response body for 200 here, so treat it as optional.
            if not r.text:
                return None
            try:
                data = r.json()
            except ValueError:
                return None
            return data if isinstance(data, dict) else None

        detail = ""
        try:
            err = r.json()
            if isinstance(err, dict) and isinstance(err.get("message"), str):
                detail = err["message"]
        except ValueError:
            detail = (r.text or "")[:500]
        raise ApiHttpError(r.status_code, url, detail or "(no body)")


    def login_for_suki_token(partner_id: str, partner_token: str, *, provider_id: Optional[str] = None) -> str:
        url = f"{BASE_URL}/api/v1/auth/login"
        body: dict[str, Any] = {"partner_id": partner_id, "partner_token": partner_token}
        if provider_id is not None:
            body["provider_id"] = provider_id
        r = requests.post(url, json=body, headers={"Content-Type": "application/json"}, timeout=60)
        if r.status_code != 200:
            raise ApiHttpError(r.status_code, url, (r.text or "")[:500] or "(no body)")
        data = r.json()
        token = data.get("suki_token") if isinstance(data, dict) else None
        if not isinstance(token, str) or not token:
            raise ValueError(f"{url}: 200 response missing suki_token")
        return token


    def seed_form_filling_session_context(
        suki_token: str,
        ambient_session_id: str,
        body: Optional[FormFillingSessionContext] = None,
    ) -> None:
        url = f"{BASE_URL}/api/v1/form-filling/session/{ambient_session_id}/context"
        headers = {"sdp_suki_token": suki_token, "sdp_provider_id": "<sdp_provider_id>", "Content-Type": "application/json"}
        _post_json_expect(url, headers, dict(body or {}), 200)


    if __name__ == "__main__":
        try:
            token = login_for_suki_token("<partner_id>", "<partner_token>")

            # Body is optional. Example shows one required form template ID inside `form_filling.values`.
            seed_form_filling_session_context(
                token,
                ambient_session_id="<ambient_session_id>",
                body={
                    "form_filling": {
                        "values": [
                            {"form_template_id": "019d4cdc-9319-7d81-ae2e-fd6de7f1b4f0"},
                        ]
                    }
                },
            )
            print("Context seeded.")
        except (ApiHttpError, ValueError) as e:
            print(e)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript expandable theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
    const BASE_URL = "https://sdp.suki-stage.com";

    type AuthenticationRequest = {
      partner_id: string;
      partner_token: string;
      provider_id?: string;
    };

    type AuthenticationResponse = { suki_token: string };

    type FormFillingMetadata = { form_template_id: string };
    type FormFillingContext = { values: FormFillingMetadata[] };
    type FormFillingSessionContext = {
      // Optional, but if provided, `values` and `form_template_id` are required.
      form_filling?: FormFillingContext;
    };

    async function postJsonExpectOptional(
      url: string,
      init: RequestInit,
      expectStatus: number,
    ): Promise<{ json?: Record<string, unknown>; text?: string }> {
      const res = await fetch(url, init);
      const text = await res.text();

      if (res.status !== expectStatus) {
        let msg = text.slice(0, 500);
        try {
          const data: unknown = text ? JSON.parse(text) : null;
          if (data && typeof data === "object" && "message" in data) {
            msg = String((data as { message?: string }).message ?? msg);
          }
        } catch {
          // keep raw text
        }
        throw new Error(`HTTP ${res.status} ${url}: ${msg || "(no body)"}`);
      }

      // OpenAPI does not define a response body for 200 here, so treat it as optional.
      if (!text) return {};

      try {
        const data: unknown = JSON.parse(text);
        if (data && typeof data === "object") return { json: data as Record<string, unknown>, text };
        return { text };
      } catch {
        return { text };
      }
    }

    async function loginForSukiToken(body: AuthenticationRequest): Promise<string> {
      const url = `${BASE_URL}/api/v1/auth/login`;
      const { json } = await postJsonExpectOptional(
        url,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
        },
        200,
      );

      const token = json?.suki_token;
      if (typeof token !== "string" || !token) throw new Error(`${url}: missing suki_token`);
      return token;
    }

    async function seedFormFillingSessionContext(
      sukiToken: string,
      ambientSessionId: string,
      body: FormFillingSessionContext = {},
    ): Promise<void> {
      const url = `${BASE_URL}/api/v1/form-filling/session/${ambientSessionId}/context`;
      await postJsonExpectOptional(
        url,
        {
          method: "POST",
          headers: {
            sdp_suki_token: sukiToken, sdp_provider_id: "<sdp_provider_id>",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        },
        200,
      );
    }

    async function main(): Promise<void> {
      try {
        const token = await loginForSukiToken({
          partner_id: "<partner_id>",
          partner_token: "<partner_token>",
        });

        // Body is optional. Example shows one required form template ID inside `form_filling.values`.
        await seedFormFillingSessionContext(token, "<ambient_session_id>", {
          form_filling: {
            values: [{ form_template_id: "019d4cdc-9319-7d81-ae2e-fd6de7f1b4f0" }],
          },
        });

        console.log("Context seeded.");
      } catch (e) {
        console.error(e instanceof Error ? e.message : e);
      }
    }

    void main();
    ```
  </Tab>
</Tabs>


## OpenAPI

````yaml POST /api/v1/form-filling/session/{ambient_session_id}/context
openapi: 3.0.1
info:
  title: Suki Developer Platform
  description: >-
    REST and WebSocket APIs for the Suki Developer Platform. Authenticate with
    Login or Register to obtain a Suki access token, then integrate ambient
    clinical documentation, form filling, transcription, and reference metadata
    endpoints.
  contact: {}
  version: '1.0'
servers:
  - url: https://sdp.suki.ai
    description: >-
      Production base URL for Suki Developer Platform REST APIs. WebSocket
      endpoints use the same host with `wss://`.
security:
  - SukiTokenAuth: []
paths:
  /api/v1/form-filling/session/{ambient_session_id}/context:
    post:
      tags:
        - /api/v1/form-filling/session
      summary: Seed form-filling session context
      description: >-
        Seeds form template metadata for a form-filling session before audio
        capture. Include `form_filling.values` with a `form_template_id` for
        each template.
      parameters:
        - name: ambient_session_id
          in: path
          description: >-
            Form-filling session ID. The path parameter is named
            `ambient_session_id`, but this value identifies the form-filling
            session, not an ambient clinical documentation session. Use the ID
            returned from Create Form Filling Session, or the UUID you supplied
            in that request.
          required: true
          schema:
            type: string
        - $ref: '#/components/parameters/ProviderIdHeader'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/controllers.FormFillingSessionContext'
        required: false
      responses:
        '200':
          description: Request succeeded.
          content:
            application/json:
              schema:
                type: object
                properties: {}
              examples:
                default:
                  summary: Success
                  value: {}
        '400':
          description: Bad request. The request body or parameters failed validation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/controllers.BadRequestError'
        '401':
          description: Unauthorized. The Suki access token is missing, expired, or invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/controllers.AuthenticationError'
        '403':
          description: Forbidden. The authenticated user cannot access this resource.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/controllers.ForbiddenError'
        '404':
          description: Not found. The session, encounter, or resource ID does not exist.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/controllers.NotFoundError'
        '500':
          description: Internal server error.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/controllers.InternalServerError'
      security:
        - SukiTokenAuth: []
      x-codeSamples:
        - lang: bash
          label: cURL
          source: |-
            curl --request POST \
              --url https://sdp.suki.ai/api/v1/form-filling/session/<ambient_session_id>/context \
              --header 'Content-Type: application/json' \
              --header 'sdp_suki_token: <sdp_suki_token>' \
              --header 'sdp_provider_id: <sdp_provider_id>'
components:
  parameters:
    ProviderIdHeader:
      name: sdp_provider_id
      in: header
      description: >-
        **Optional** - Stable identifier for the active provider. Omit for
        standard partners whose `partner_token` identifies the user.
        **Required** for Bearer partners and Single Auth Token authentication
        where multiple providers share one `partner_token`. Use the same
        `provider_id` you sent on Login or Register.
      required: false
      schema:
        type: string
        example: provider-123
  schemas:
    controllers.FormFillingSessionContext:
      type: object
      properties:
        form_filling:
          description: >-
            **Optional** - Form template metadata for the form-filling session,
            including required `form_template_id` values.
          allOf:
            - $ref: '#/components/schemas/controllers.FormFillingContext'
      description: >-
        Form template metadata for the form-filling session, including
        `form_filling.values` with required `form_template_id` entries.
    controllers.BadRequestError:
      type: object
      properties:
        code:
          type: integer
          example: 400
          description: HTTP status code for the error.
        message:
          type: string
          example: invalid request
          description: Human-readable description of the validation or request error.
      description: Error response when the request fails validation.
    controllers.AuthenticationError:
      type: object
      properties:
        code:
          type: integer
          example: 401
          description: HTTP status code for the error.
        message:
          type: string
          example: invalid token
          description: Human-readable description of the authentication failure.
      description: Error response when authentication fails.
    controllers.ForbiddenError:
      type: object
      properties:
        code:
          type: integer
          example: 403
          description: HTTP status code for the error.
        message:
          type: string
          example: forbidden
          description: Human-readable description of the authorization failure.
      description: Error response when the caller lacks permission.
    controllers.NotFoundError:
      type: object
      properties:
        code:
          type: integer
          example: 404
          description: HTTP status code for the error.
        message:
          type: string
          example: not found
          description: Human-readable description of the missing resource.
      description: Error response when the requested resource was not found.
    controllers.InternalServerError:
      type: object
      properties:
        code:
          type: integer
          example: 500
          description: HTTP status code for the error.
        message:
          type: string
          example: internal server error
          description: Human-readable description of the server error.
      description: Error response when the server encounters an unexpected error.
    controllers.FormFillingContext:
      type: object
      description: Information about form-filling context
      required:
        - values
      properties:
        values:
          description: Array of form template metadata.
          type: array
          items:
            $ref: '#/components/schemas/controllers.FormFillingMetadata'
    controllers.FormFillingMetadata:
      type: object
      required:
        - form_template_id
      properties:
        form_template_id:
          description: Form template ID (UUID).
          type: string
          example: 019d4cdc-9319-7d81-ae2e-fd6de7f1b4f0
  securitySchemes:
    SukiTokenAuth:
      type: apiKey
      in: header
      name: sdp_suki_token
      description: >-
        Suki access token for the authenticated provider. Obtain this by calling
        Login or Register with a valid `partner_token`. Pass the `suki_token`
        value from the JSON response as the `sdp_suki_token` header on REST
        requests and non-browser WebSocket upgrades. Browser WebSocket clients
        pass the token in `Sec-WebSocket-Protocol` instead. Tokens expire after
        one hour; call Login again to refresh.

````