Integration guide

KSeF API Java integration guide

Send a KSeF FA(3) invoice from Java 11+ with the Notaly API: java.net.http.HttpClient, idempotency, error codes and status polling.

Updated

Overview

From Java 11 onwards you can send a KSeF invoice through Notaly with the built-in java.net.http.HttpClient, with no Maven or Gradle dependency. You post plain JSON to https://api.getnotaly.com/invoices, and Notaly generates the FA(3) XML, checks it against the official XSD (the same check as our FA(3) validator) and submits it to KSeF.

What do you need before you start?

  • A sandbox account and its API key, stored in the NOTALY_API_KEY environment variable rather than in the source file.
  • The seller NIP. In the sandbox it is fixed to 2745013933, and any other seller NIP returns 422 seller_nip_not_authorized before anything reaches KSeF. If you have already connected your own KSeF Demo token, use your connected NIP instead.
  • A buyer NIP in BUYER_NIP: no default, 10 digits. Use a buyer NIP you are entitled to use: on KSeF Demo the invoice is visible to that NIP.

Today the API accepts only currency: "PLN" (other codes get 422 currency_not_supported) and the VAT rates 23, 8, 5 and 0 (domestic 0%, written as "0 KR"; export and intra-EU 0% are not supported). A unit is required on every line.

How do you send the invoice from Java?

Reference example, statically checked against the API contract but not executed by us; adjust and test it in your sandbox account.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NotalyInvoice {
    static final String API = "https://api.getnotaly.com/invoices";
    static final String SELLER_NIP = "2745013933"; // sandbox seller NIP; with a KSeF Demo connection use your connected NIP
    // Polish letters built from code points keep this file pure ASCII
    static final String L = String.valueOf((char) 0x0142); // l with stroke
    static final String O = String.valueOf((char) 0x00F3); // o with acute

    public static void main(String[] args) throws Exception {
        String apiKey = requireEnv("NOTALY_API_KEY");
        String buyerNip = requireEnv("BUYER_NIP");
        if (!buyerNip.matches("\\d{10}")) throw new IllegalStateException("BUYER_NIP must be 10 digits");
        String number = "FV/2026/10/001";
        // Issue date = today in Poland, not the server's local or UTC date
        String issueDate = LocalDate.now(ZoneId.of("Europe/Warsaw")).toString();

        // Amounts are JSON literals. If you compute them, use BigDecimal, never double/float.
        String json = "{"
            + "\"number\":\"" + number + "\","
            + "\"issueDate\":\"" + issueDate + "\","
            + "\"currency\":\"PLN\","
            + "\"seller\":{\"nip\":\"" + SELLER_NIP + "\",\"name\":\"Your company\","
            + "\"address\":{\"line1\":\"ul. Przyk" + L + "adowa 1, 00-001 Warszawa\",\"country\":\"PL\"}},"
            + "\"buyer\":{\"nip\":\"" + buyerNip + "\",\"name\":\"Test Customer\","
            + "\"address\":{\"line1\":\"ul. Pr" + O + "bna 2, 30-001 Krak" + O + "w\",\"country\":\"PL\"}},"
            + "\"items\":[{\"name\":\"Consulting\",\"unit\":\"h\",\"quantity\":2,\"unitNetPrice\":200,\"vatRate\":23}]"
            + "}";

        HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
        HttpRequest post = HttpRequest.newBuilder(URI.create(API))
            .timeout(Duration.ofSeconds(30))
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            // one key per invoice, derived from its number: reuse it on every retry of this invoice
            .header("Idempotency-Key", "demo-" + number.replace('/', '-'))
            .POST(HttpRequest.BodyPublishers.ofString(json)) // sent as UTF-8
            .build();

        HttpResponse<String> res = http.send(post, HttpResponse.BodyHandlers.ofString());
        if (res.statusCode() / 100 != 2) {
            System.err.println("HTTP " + res.statusCode() + ": " + field(res.body(), "error"));
            String message = field(res.body(), "message");
            if (message != null) System.err.println(message); // e.g. a body that does not match the schema
            System.err.println(res.body()); // includes details[] for validation_failed / xsd_invalid
            System.exit(1);
        }

        String id = field(res.body(), "id");
        String status = field(res.body(), "status");
        String error = field(res.body(), "error");
        System.out.println("Invoice " + id + ": " + status + " (number " + field(res.body(), "number") + ")");

        HttpRequest get = HttpRequest.newBuilder(URI.create(API + "/" + id))
            .timeout(Duration.ofSeconds(30))
            .header("Authorization", "Bearer " + apiKey)
            .GET()
            .build();
        // Poll while submitted (every 5 s) or draft + ksef_submitting (every 30 s): Notaly resends that draft itself,
        // which can take several minutes. Never send a new POST for it. In production prefer webhooks.
        for (int i = 0; i < 60 && ("submitted".equals(status) || ("draft".equals(status) && "ksef_submitting".equals(error))); i++) {
            if ("submitted".equals(status) && "ksef_duplicate_review".equals(error)) break;
            Thread.sleep("draft".equals(status) ? 30000 : 5000);
            String body = http.send(get, HttpResponse.BodyHandlers.ofString()).body();
            status = field(body, "status");
            error = field(body, "error");
            if ("rejected".equals(status)) System.err.println("Rejected: " + error);
        }
        if ("draft".equals(status)) {
            System.err.println("Draft (" + error + "): do not create a new invoice. If ksef_submitting, Notaly is resending it, so check GET /invoices/" + id + "; otherwise write to hello@getnotaly.com with the invoice id.");
            System.exit(1);
        }
        if ("submitted".equals(status) && "ksef_duplicate_review".equals(error))
            System.err.println("ksef_duplicate_review: KSeF already has this invoice from an earlier attempt. Do not reissue it with another number; Notaly links it to the KSeF record.");
        System.out.println("Status: " + status);
        System.exit("accepted".equals(status) ? 0 : 1);
    }

    static String requireEnv(String name) {
        String v = System.getenv(name);
        if (v == null || v.isBlank()) throw new IllegalStateException("Set " + name);
        return v;
    }

    // Minimal top-level string field reader for this example; use Jackson or Gson in real code
    static String field(String json, String name) {
        Matcher m = Pattern.compile("\"" + name + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json);
        return m.find() ? m.group(1) : null;
    }
}

Run it with NOTALY_API_KEY=... BUYER_NIP=... java NotalyInvoice.java; since Java 11 a single source file launches without a separate compile step. Three details in the code are deliberate:

  • ASCII-only source. The Polish letters in the addresses are built from their code points ((char) 0x0142 and (char) 0x00F3), so the file contains no non-ASCII byte. BodyPublishers.ofString sends the body as UTF-8, so the API gets the correct address even when the file is compiled with a non-UTF-8 default encoding, as can happen on Windows with JDK 11 to 17.
  • Amounts. They are literals inside the JSON. If you calculate them, use BigDecimal: double and float can shift amounts by a fraction of a grosz.
  • Issue date. It comes from ZoneId.of("Europe/Warsaw"), because close to midnight the server's local or UTC date can already be a different day.

What does the response tell you?

Check status on every 2xx response before you mark the invoice as sent. Each outcome needs a different reaction:

ResponseWhat it meansWhat your code should do
status: "submitted"KSeF received the invoice and returned a reference number.Poll GET /invoices/{id}, as the loop does, or wait for a webhook.
Same Idempotency-Key as an earlier callThe invoice already stored comes back and nothing new is created.Treat it as the same invoice. This is what makes retries safe.

If the response is draft with error: "ksef_submitting", KSeF has not confirmed the submission yet. Do not send a new POST and do not issue the invoice again under a new number: Notaly resends the same XML automatically. Poll GET /invoices/{id} until the status is submitted. Such a draft already counts towards the three sandbox invoices. If the status is submitted with error: "ksef_duplicate_review", KSeF already has this invoice from an earlier attempt. Do not reissue it with another number; we link it to the KSeF record on our side. If you need it sooner, write to hello@getnotaly.com with the invoice id. If the invoice is draft with error: "ksef_retry_exhausted", Notaly has stopped resending it automatically (after 24 hours, or earlier if KSeF returned a definitive error). Do not create a new invoice: write to hello@getnotaly.com with the invoice id, and we check in KSeF whether it arrived before anything is resent. If an invoice is still draft with error: null or ksef_unavailable after about a minute, Notaly does not resend it: do not create a new invoice; write to hello@getnotaly.com with the invoice id.

Derive the key from the invoice number, as the code does (demo-FV-2026-10-001). A fresh UUID.randomUUID() on every call protects nothing.

> In the sandbox the returned number carries a short suffix, for example FV/2026/10/001/ab12cd34, so do not compare it with the number you sent.

What if the request times out?

http.send throws HttpTimeoutException (a subclass of IOException) when the 30-second timeout passes, and a plain IOException when the connection drops. At that point you cannot tell whether the API stored the invoice. Catch the exception and repeat the same POST with the same Idempotency-Key: if the invoice was stored, you get it back; if not, it is created now. Never generate a new key for this kind of retry. If the retry comes back as status: "draft" with error: "ksef_submitting", the first request is still being sent to KSeF: poll GET /invoices/{id} as described above. Do not create a new invoice in the meantime, or the same sale may reach KSeF twice. Lengthen the pause between attempts, for example 2, 4 and 8 seconds, and give up after a few tries.

Which error codes should you handle?

Branch on the error code, never on the message text, which can change. A body that does not match the schema (a missing field, a wrong type, a VAT rate outside 23/8/5/0 or an issueDate not in YYYY-MM-DD) gets 422 validation_failed with a message before any other check. After that the API checks, in this order: 422 currency_not_supported, 422 unit_required, then 422 validation_failed with a details array. Next come the connection codes: 422 ksef_not_connected, ksef_connection_pending and ksef_connection_invalid mean you need to connect, validate or reconnect your KSeF token in the dashboard; ksef_production_disabled means KSeF production is switched off in Notaly right now, so nothing was sent; ksef_plan_required means the account needs a paid plan. After those come 422 seller_nip_not_authorized, 402 quota_exceeded and 422 xsd_invalid (with details; nothing was sent or counted).

Treat a 503 (ksef_unavailable or validator_unavailable) like a timeout: nothing was stored, so wait and retry with the same key. A 401 means NOTALY_API_KEY is missing or wrong; fix the variable instead of retrying.

How do you follow the invoice to the end?

While status stays submitted, the loop calls GET /invoices/{id} every 5 seconds; while it is draft with ksef_submitting, every 30 seconds. It makes at most 60 checks and never sends a new POST. It stops on submitted with ksef_duplicate_review, on any other draft and on a final status. An invoice moves from draft to submitted and ends as accepted or rejected. Once accepted it carries ksefNumber and pdfUrl, and Notaly requests the UPO and adds it to the invoice when KSeF issues it. A rejection comes with a stable code such as ksef_rejected:<code>, which you can store and show to the user. For production traffic, replace the loop with webhooks.

Notaly validates and submits invoices. It is not a tax, accounting or legal advisor, and VAT rates and tax classification remain your responsibility.

Summary

  • One file, Java 11+, java.net.http.HttpClient, no Maven or Gradle.
  • NOTALY_API_KEY and BUYER_NIP are required; sandbox seller NIP 2745013933.
  • ASCII source (Polish letters from code points), BigDecimal for any computed amount, issue date from Europe/Warsaw.
  • After the POST, read status and error: submitted → poll or webhook; draft + ksef_submitting → keep polling, never a new POST; submitted + ksef_duplicate_review → do not reissue; draft + ksef_retry_exhausted → write to hello@getnotaly.com with the invoice id.
  • On a timeout or 503, retry with the same key; branch on error codes, never on messages.

Sources

Source: www.podatki.gov.pl

Frequently asked questions

Which Java version do I need?

Java 11 or newer. The example uses java.net.http.HttpClient and java.time, and runs as a single file with java NotalyInvoice.java, with no Maven or Gradle.

Should I parse JSON with regular expressions?

Only in a short example like this one. In your application use a JSON library such as Jackson or Gson, and BigDecimal for amounts.

Issue your first KSeF test invoice today

Create a sandbox account: API key in seconds, 3 free test invoices on KSeF TEST, no credit card.