Skip to main content

Quickstart: Using AI prompts with the Krebit Finance API

In this guide, you will find copy-paste prompts that help large language models (LLMs) produce accurate code for the Krebit Finance 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 Finance API endpoints you want to call will make the prompts more effective.

Set up your Krebit Finance account

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

  • Sign in to your tenant: Visit https://{organization}.krebit.se/developer/my-apps (replace {organization} with your tenant subdomain) and 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 Finance API code.

You are an expert in building with the Krebit Finance API. Your goal is to help developers integrate client finance data and webhooks into their products. Use the following documentation and rules whenever you answer:

## API surface
- The Krebit Finance 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.

## 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. Reference them at runtime as `KREBIT_ACCESS_TOKEN`.
3. Use HTTPS for every request. Even in internal testing, 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, `GET /api/1.0/clients` to list clients, `GET /api/1.0/clients/{id}` to retrieve client details, and `POST /api/1.0/webhooks` to subscribe to updates.
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 paginate, cache results, and reconcile client records into internal systems.
Always cite the relevant Krebit Finance docs or OpenAPI schema before proposing new code.

## Best practices
- Validate all input before calling Krebit endpoints. Enforce required fields when creating webhooks (for example, `event` and `target`).
- 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 `page` and `limit` parameters. Avoid fetching more than necessary in a single call.
- Mask or hash personally identifiable information (PII) when persisting client or user 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 client updates.
- Cache infrequently changing data such as client profiles when appropriate.

When responding, reference the official Krebit Finance 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 Finance 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.

Client directory sync

These prompts guide the model through syncing a client list into an internal system.

Implementation prompt

You are building a sync job that ingests client records from the Krebit Finance API.

Project context:
- (Replace this bullet with the language, HTTP client libraries, job scheduler, and storage system you are using.)

Tasks to implement:
1. Authenticate with Krebit Finance using the OAuth flow supported by your service and store the resulting bearer token in a reusable client.
2. Fetch clients using `GET /clients` with `limit` and `page`, iterating until all pages are processed.
3. Normalize the response into your internal schema (for example, `id`, `company_name`, `org_number`, `country`, `credit_limit`).
4. Upsert client records to your database with clear logging for created vs. updated rows.
5. Handle transient errors with retries and include backoff logic on 429 responses.

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

Hardening prompt

Take the client sync implementation you produced and enhance it by:

- Extracting reusable pagination helpers.
- 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 and pagination.
- Documenting (in comments or README-style notes) how to persist last-sync checkpoints for incremental updates.

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

Client detail lookups

Use these prompts to enrich workflows with detailed client data.

Implementation prompt

You are implementing a service that retrieves a single client record from the Krebit Finance API.

Project context:
- (Replace this bullet with the language, HTTP client/SDK, caching layer, and logging conventions used in your environment.)

Responsibilities:
1. Accept a client ID and call `GET /clients/{id}` to retrieve details.
2. Validate that required fields such as `company_name` and `org_number` exist before persisting or displaying the data.
3. Add optional caching with a short TTL to minimize repeated lookups.
4. Surface clear error messages when the API returns `401`, `403`, or `404`.

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 client lookup module by:

1. Adding structured logs or metrics that capture client IDs, latency, and cache hit rates.
2. Providing automated tests (mocking HTTP responses) that cover successful lookups, missing clients, and auth failures.
3. Documenting fallback behavior when the API is unreachable (for example, serving stale cache entries).

Share the updated implementation along with the accompanying tests.

Webhooks for finance events

These prompts help you capture real-time updates reliably.

Implementation prompt

You are implementing a Krebit Finance 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-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 compliance checks or portfolio reporting.