Skip to main content

Quickstart: Using AI prompts with the Krebit Sign API

In this guide, you will find copy-paste prompts that help large language models (LLMs) produce accurate code for the Krebit Sign API. Use them inside AI-enabled IDEs (Cursor, GitHub Copilot, Zed, Windsurf, and similar tools) to bootstrap working integrations that follow Krebit's conventions and best practices.

Prerequisites

For this guide, assume that you are prompting an LLM through an AI-focused IDE. If you are evaluating different tools, read the following references:

A basic understanding of the Krebit Sign API endpoints you want to call will make the prompts more effective.

Set up your Krebit Sign account

Do the following tasks before asking the LLM to generate code:

  • Create a Krebit organization: Visit https://{organization}.krebit.se/developer/my-apps (replace {organization} with your tenant name) and register or sign in.
  • Register an OAuth application: Create an app from the developer portal to obtain a client_id and client_secret. Store them as KREBIT_CLIENT_ID and KREBIT_CLIENT_SECRET in your environment.
  • Choose a redirect URI: Define where Krebit should send users after they approve access. Save it as KREBIT_REDIRECT_URI and add the same value to your app's callback settings.
  • Capture your base domain: Save your tenant domain (for example, yourco.krebit.se) as KREBIT_ORGANIZATION_DOMAIN. The base API URL becomes https://$KREBIT_ORGANIZATION_DOMAIN and all REST endpoints live under /api/1.0.
  • Protect your secrets: Use a .env file or a secrets manager. Never hard-code credentials inside client-side or shared code snippets.

With these pieces in place, you can guide an LLM to acquire tokens and call authenticated endpoints.

Starter prompt

Copy the following prompt into your LLM to establish the correct context before generating any Krebit Sign API code.

You are an expert in building with the Krebit Sign API. Your goal is to help developers quickly build digital signing workflows for their SaaS applications. Use the following documentation and rules whenever you answer:

## API surface
- The Krebit Sign API base URL is `https://{organization}.krebit.se/api/1.0`. Replace `{organization}` with the tenant subdomain (for example, `yourco.krebit.se`).
- Authentication uses the OAuth 2.0 Authorization Code flow. Users grant access through `https://{organization}.krebit.se/oauth/authorize`, and the backend exchanges the authorization code for tokens at `https://{organization}.krebit.se/oauth/token`.
- Every API request must include `Authorization: Bearer <access_token>` and `Accept: application/json`. Use `Content-Type: application/json` for JSON payloads and `multipart/form-data` when uploading documents.

## Environment setup
1. Read `KREBIT_CLIENT_ID`, `KREBIT_CLIENT_SECRET`, `KREBIT_REDIRECT_URI`, and `KREBIT_ORGANIZATION_DOMAIN` from environment variables. Build `KREBIT_BASE_URL = https://$KREBIT_ORGANIZATION_DOMAIN` and append `/api/1.0` for REST endpoints.
2. After exchanging the authorization code, store the returned `access_token` (and optional `refresh_token`) securely—never commit them to source control. Reference them at runtime as `KREBIT_ACCESS_TOKEN`.
3. Use HTTPS for every request. If you are running against a non-production tenant, still rely on TLS and valid redirect URIs.
4. Only persist tokens or user-specific data in your database after encrypting at rest and limiting access.

## Implementation steps
1. **Implement OAuth**: Generate the authorization URL with the registered redirect URI and a CSRF-resistant `state` value. Handle the callback, verify `state`, and call `POST /oauth/token` with `grant_type=authorization_code` to obtain bearer tokens.
2. **Create a reusable HTTP client**: Configure the client with the `Authorization` header and JSON defaults. Consider automatically refreshing tokens by calling `POST /oauth/token` with `grant_type=refresh_token`.
3. **Call Krebit endpoints**: Show working examples that use `/api/1.0` routes—`GET /api/1.0/me` to validate authentication, `POST /api/1.0/signings` to create drafts, `POST /api/1.0/signings/{uuid}/documents` to upload PDFs, `POST /api/1.0/signings/{uuid}/recipients` to add signers, and `POST /api/1.0/signings/{uuid}/send` to trigger delivery.
4. **Handle responses**: Parse JSON payloads, inspect `request_id` fields when present, and surface useful status to the caller. Map HTTP status codes to actionable error messages.
5. **Plan extensions**: Suggest how to read signing status, download completed documents, set up webhooks, or cancel a signing.
Always cite the relevant Krebit Sign docs or OpenAPI schema before proposing new code.

## Best practices
- Validate all input before calling Krebit endpoints. Enforce required fields (for example, signing `name`, `language`, and signer `email`).
- Guard critical operations with try/catch blocks, log failures with request IDs, and back off or retry when you receive 5xx or 429 responses.
- Paginate list operations using Krebit's cursor parameters. Avoid fetching more than necessary in a single call.
- Mask or hash personally identifiable information (PII) when persisting signer details.

## Security guidelines
- Never expose `client_secret`, tokens, or webhook secrets in frontend code, logs, or generated documentation.
- Use HTTPS redirects and same-origin CSRF protections on OAuth callbacks.
- Rotate refresh tokens and webhook secrets periodically.

## Performance guidelines
- Prefer webhooks over polling when you need near real-time signing updates.
- Cache infrequently changing data such as signer profiles or signing templates when appropriate.
- Stream file uploads/downloads to avoid loading large PDFs entirely into memory.

When responding, reference the official Krebit Sign API documentation available in your Krebit developer portal (including this docs site) for authoritative details, and clarify any assumptions if the docs do not cover a topic.

How to use the feature prompts

Each workflow below includes two prompts:

  • Implementation prompt – Ask the LLM to generate the initial feature using best practices.
  • Hardening prompt – Follow up with this prompt to review the generated code, add tests, and cover edge cases before shipping.

Paste the implementation prompt first, let the model respond, then paste the hardening prompt to iterate.

Feature prompts

Before using any feature prompt, append a short description of your runtime, frameworks, deployment constraints, and coding conventions. For example, tell the LLM which language you use, how HTTP requests are performed, what testing tools are available, and how secrets/configuration are managed. This ensures the generated output fits your stack instead of defaulting to unfamiliar libraries.

Hosted OAuth and token refresh

Use these prompts to scaffold the Authorization Code flow for any backend capable of storing tokens securely and handling redirects.

Implementation prompt

You are implementing OAuth endpoints for a Krebit Sign integration.

Project context:
- (Replace this bullet with a concise overview of your runtime, frameworks, HTTP client, configuration management, and persistence strategy.)

Requirements:
1. Base tenant domain: `https://${KREBIT_ORGANIZATION_DOMAIN}`. All OAuth routes live under that origin.
2. Environment configuration: `KREBIT_CLIENT_ID`, `KREBIT_CLIENT_SECRET`, `KREBIT_REDIRECT_URI`, and `KREBIT_ORGANIZATION_DOMAIN` must be loaded from secure configuration.
3. Endpoints to expose:
- `GET /auth/krebit/start`: generate a cryptographically strong `state`, persist it for CSRF validation, and redirect to `https://$DOMAIN/oauth/authorize` with the standard Authorization Code query parameters.
- `GET /auth/krebit/callback`: validate the `state`, exchange the `code` via `POST /oauth/token` (`Content-Type: application/x-www-form-urlencoded`), and persist `access_token`, `refresh_token`, and `expires_in` using the storage layer described in the project context.
- `POST /auth/krebit/refresh`: refresh the access token when it is close to expiry by calling `/oauth/token` with `grant_type=refresh_token` and update stored credentials.
4. Provide reusable helpers for generating authorization URLs, exchanging tokens, and serializing credentials.
5. Surface structured error handling that logs Krebit `request_id` headers when provided, without leaking secrets.

Return production-ready code that fits the project context, including any supporting abstractions.

Hardening prompt

Review the Krebit OAuth implementation that was just generated and strengthen it by:

1. Adding automated tests using the project's testing stack to cover successful authorization, refresh, CSRF mismatches, and error responses (mocking outbound HTTP where appropriate).
2. Documenting, in code comments, how to rotate client credentials and webhook secrets without downtime.
3. Improving logging to emit redactable metadata (status codes, request IDs, retry hints) while omitting sensitive payloads.
4. Recommending durable storage options for tokens (e.g., encrypted database, secrets manager) that align with the project context.

Provide the updated implementation and test coverage.

Create, populate, and send a signing package

These prompts guide the model through orchestrating a complete signing workflow.

Implementation prompt

You are building a service that assembles and sends a Krebit Sign signing package.

Project context:
- (Replace this bullet with the language, HTTP/file-upload libraries, configuration patterns, and deployment environment you are using.)

Tasks to implement:
1. Authenticate with Krebit Sign using the OAuth flow supported by your service (Client Credentials for machine-to-machine or Authorization Code on behalf of a user) and store the resulting bearer token in a reusable client.
2. Create a signing draft with `{ name, language, message, signing_order }`, enforcing `language` ∈ {`EN`, `SV`} and `signing_order` ∈ {`sequential`, `parallel`}.
3. Upload a local PDF through `POST /signings/{signingId}/documents` using `multipart/form-data` with the `selected_file` field. Enforce PDF rules (≤10 MB, not password protected or previously signed).
4. Add at least two recipients with varied `signing_method` values (e.g., `email`, `bankid`, `approval`) and sequential order values when applicable. Include optional identification fields when your backend exposes them.
5. Send the signing package, then log status fields such as `is_draft`, `is_completed`, and `cancelled_at`.
6. Handle validation errors gracefully, surfacing messages from the response body and outlining where to plug in retry logic and persistence for IDs returned by the API.

Return modular code that aligns with the project context, showing how to compose these steps into a reliable workflow.

Hardening prompt

Take the signing workflow implementation you produced and enhance it by:

- Extracting reusable functions or classes for token acquisition, signing creation, document upload, recipient management, and sending.
- Adding retry logic with exponential backoff for transient 5xx or 429 responses, while keeping validation failures immediately visible.
- Writing automated tests using the project's testing framework that mock HTTP interactions to verify payloads and sequencing.
- Documenting (in comments or README-style notes) how to persist signing IDs, document IDs, and recipient IDs for later status tracking and reconciliation.

Return the refactored code together with the corresponding tests or fixtures.

Track signing status and download files

Use these prompts to build dashboards or archival automations.

Implementation prompt

You are creating a module that monitors signing progress and archives completed documents.

Project context:
- (Replace this bullet with the language, HTTP client/SDK, storage location for downloaded files, and logging/metrics conventions used in your environment.)

Responsibilities:
1. Fetch a paginated list of active signings (page size ≈20) and render `name`, `is_draft`, `is_completed`, and `updated_at`.
2. For a selected signing ID, retrieve recipients and flag anyone without a completion timestamp.
3. Download the signed PDF for each completed document via `GET /signings/{signingId}/documents/{documentId}/download-signed`, saving files using a naming scheme such as `{signingId}-{documentId}.pdf`.
4. Skip or warn on download attempts when the API returns `404` because `signed_file_path` is absent.
5. Model the signing, recipient, and document shapes locally so downstream consumers understand the data contract.

Deliver idiomatic code that fits the project context and highlights where to plug in dependency injection or background processing if needed.

Hardening prompt

Improve the monitoring and archival module by:

1. Adding caching or memoization guidance so subsequent dashboard loads avoid redundant API calls when data is unchanged.
2. Emitting structured logs or metrics that capture signing IDs, document IDs, download statuses, and error details.
3. Providing automated tests (mocking HTTP responses and file writes) that ensure signed documents are saved correctly and incomplete documents are skipped.
4. Documenting how to integrate the module with background workers, task queues, or schedulers for regular syncs.

Share the updated implementation along with the accompanying tests.

Webhooks for signing lifecycle events

These prompts help you capture real-time updates reliably.

Implementation prompt

You are implementing a Krebit Sign webhook receiver.

Project context:
- (Replace this bullet with the language/framework, routing or serverless platform, logging approach, and dependency injection patterns that apply.)

Implementation requirements:
1. Expose an HTTP endpoint such as `POST /webhooks/krebit` that accepts raw JSON bodies.
2. Validate the `X-Krebit-Signature` header using HMAC-SHA256 and the shared secret (`KREBIT_WEBHOOK_SECRET`) stored securely. Reject requests with invalid signatures.
3. Parse the event payload, enqueue or hand off to your background processing mechanism, and respond with `202 Accepted`.
4. Log structured metadata (`event.id`, `event.type`, `received_at`) without leaking sensitive data.
5. Outline how to retry transient failures from within your infrastructure.

Return production-grade handler code that matches the project context, including signature verification helpers.

Hardening prompt

Strengthen the webhook handler by:

- Adding idempotency safeguards (e.g., storing processed event IDs) to prevent duplicate processing.
- Creating integration or contract tests using your project's testing tools to cover valid deliveries, invalid signatures, and replay attempts.
- Documenting a strategy for rotating webhook secrets and deploying the update without downtime.
- Suggesting scaling patterns for the downstream queue or worker pool (dead-letter handling, concurrency controls).

Deliver the improved handler along with the relevant tests or configuration notes.

Use these prompts as building blocks—tailor the project-context bullet before each prompt to align with your stack, or extend them to cover additional workflows such as cancellation, reminders, or analytics exports.