Getting started overview
Kroki provides an HTTP API for rendering diagrams from textual descriptions. This guide focuses on quickly getting started with the public Kroki instance, which is suitable for non-commercial use and testing. For production environments or commercial applications, self-hosting a Kroki server is recommended Kroki installation guide. The API supports numerous diagram types, including UML, sequence diagrams, flowcharts, and more, by integrating with various underlying diagramming tools Kroki supported diagrams.
The core interaction involves sending a POST request with the diagram's textual definition and specifying the diagram type and output format. Kroki then returns the rendered diagram as an image. This process simplifies diagram generation by allowing developers to define complex visualizations using code, which can be version-controlled and integrated into automated workflows.
Here's a quick reference for the steps to get started:
| Step | What to do | Where |
|---|---|---|
| 1. Review API Access | Understand the public instance usage policy. | Kroki documentation homepage |
| 2. Choose Diagram Type | Select a diagramming tool (e.g., PlantUML, Mermaid) and format. | Kroki supported diagrams list |
| 3. Prepare Diagram Code | Write your diagram definition in the chosen tool's syntax. | Kroki examples gallery |
| 4. Construct API Request | Formulate the HTTP POST request with base64-encoded diagram code. | Kroki HTTP API reference |
| 5. Make First Call | Send the request to the public Kroki instance. | Command line (curl), browser, or programming language |
| 6. Handle Response | Process the image data returned by the API. | Your application or script |
Create an account and get keys
For the public Kroki instance, there is no account creation process or API key requirement. Kroki operates as a public service for non-commercial use, allowing immediate access to its diagram rendering capabilities without authentication. This simplifies the initial setup, enabling developers to quickly integrate and test diagram generation. The public instance is hosted at https://kroki.io.
If you plan to use Kroki for commercial purposes, require higher availability, or need to process sensitive data, self-hosting is the recommended approach. When self-hosting, you manage the server instance, and thus, authentication mechanisms (if any) would be configured within your own infrastructure. Kroki itself does not provide built-in user authentication or API key management for self-hosted instances; security would typically be handled at the network or application layer preceding the Kroki server.
For details on setting up a self-hosted instance, refer to the Kroki installation documentation. This typically involves deploying a Docker container or running the JAR file directly. Once self-hosted, your API endpoint will be the URL of your deployed server, for example, http://localhost:8000 if running locally.
Your first request
To make your first request, you'll need to define a diagram using a supported language, encode it, and send it as an HTTP POST request to the Kroki endpoint. We'll use a simple Mermaid sequence diagram as an example.
1. Choose a Diagram Type and Write Diagram Code
Let's create a basic Mermaid sequence diagram. The diagram definition will be:
sequenceDiagram
Alice->>Bob: Hello Bob, how are you?
Bob-->>Alice: I am good thanks!
2. Encode the Diagram Code
Kroki expects the diagram code to be compressed using zlib and then base64-encoded. While you can do this manually, it's often easier to use a utility or library in your programming language. For demonstration purposes with curl, we'll show a direct approach, but note that for complex diagrams, a proper encoding utility is better.
The Kroki documentation provides a convenient encoding utility example for JavaScript. For a quick test, you can use an online base64 encoder, but remember to compress first for production use. For simplicity in this first call example, we will use a non-compressed, plain base64 encoding, which Kroki also supports for small payloads, although it is less efficient.
Base64 encoding of sequenceDiagram
Alice->>Bob: Hello Bob, how are you?
Bob-->>Alice: I am good thanks!
results in c2VxdWVuY2VEaWFncmFtCiAgICBBbGljZS0mZ3Q7Jmd0O0JvYjogSGVsbG8gQm9iLCBob3cgYXJlIHlvdT8KICAgIEJvYi0tJmd0OztndDtBbGljZTogSSBhbSBnb29kIHRoYW5rcyE=.
3. Construct the API Endpoint URL
The endpoint structure is https://kroki.io/{diagram_type}/{output_format}. For our example, it will be https://kroki.io/mermaid/svg.
4. Make the Request using curl
Using curl, you can send a POST request with the base64-encoded diagram. The diagram content should be sent in the request body.
curl -X POST \
-H "Content-Type: text/plain" \
--data "c2VxdWVuY2VEaWFncmFtCiAgICBBbGljZS0mZ3Q7Jmd0O0JvYjogSGVsbG8gQm9iLCBob3cgYXJlIHlvdT8KICAgIEJvYi0tJmd0OztndDtBbGljZTogSSBhbSBnb29kIHRoYW5rcyE=" \
https://kroki.io/mermaid/svg > diagram.svg
This command sends the diagram definition to Kroki, which processes it and returns an SVG image. The > diagram.svg part saves the output directly to a file named diagram.svg. You can then open this file in a web browser or an SVG viewer to see your generated diagram.
Example with JavaScript (Node.js)
For programmatic usage, you would typically use a library to handle compression and encoding. Here's a Node.js example using zlib and btoa (or a base64 library for Node.js environments).
const zlib = require('zlib');
const util = require('util');
const fetch = require('node-fetch'); // npm install node-fetch
const deflateRaw = util.promisify(zlib.deflateRaw);
async function generateKrokiDiagram() {
const diagramCode = `sequenceDiagram
Alice->>Bob: Hello Bob, how are you?
Bob-->>Alice: I am good thanks!
`;
try {
// Compress with zlib (deflateRaw) and then base64 encode
const compressed = await deflateRaw(Buffer.from(diagramCode, 'utf8'));
const encoded = Buffer.from(compressed).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
const krokiUrl = `https://kroki.io/mermaid/svg`;
const response = await fetch(krokiUrl, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: encoded
});
if (!response.ok) {
throw new Error(`Kroki API error: ${response.statusText}`);
}
const svgContent = await response.text();
console.log(svgContent); // Or save to a file
} catch (error) {
console.error('Error generating diagram:', error);
}
}
generateKrokiDiagram();
Common next steps
After successfully generating your first diagram, consider these common next steps to further integrate Kroki into your workflow:
- Explore More Diagram Types: Kroki supports a wide array of diagramming tools. Experiment with different types like PlantUML for more complex UML diagrams, Graphviz for graph visualizations, or Excalidraw for hand-drawn style diagrams Kroki documentation on supported diagrams. Each tool has its own syntax and capabilities, offering flexibility for various visualization needs.
- Integrate with Documentation Tools: Many static site generators and documentation platforms (e.g., MkDocs, Hugo, Sphinx) have plugins or extensions that can integrate with Kroki. These integrations allow you to embed diagram definitions directly into your Markdown or reStructuredText files, with the diagrams being rendered dynamically during site generation. For instance, the MkDocs documentation often covers extensions for diagramming.
- Self-Host Kroki: For production environments, improved performance, or to process sensitive data, consider deploying your own Kroki server instance. This gives you full control over the environment and resources. The Kroki installation guide provides instructions for Docker, Java JAR, and other deployment methods.
- Implement Advanced Encoding: For larger or more complex diagrams, optimize your API calls by implementing the recommended zlib compression before base64 encoding. This reduces payload size and improves request efficiency. Refer to the Kroki HTTP API documentation on encoding for detailed instructions and examples.
- Error Handling and Caching: Implement robust error handling in your applications to manage cases where Kroki might return an error (e.g., invalid diagram syntax). Additionally, consider caching generated diagrams to reduce redundant API calls and improve application responsiveness, especially for diagrams that don't change frequently.
- Explore Client Libraries: While Kroki doesn't offer official SDKs, community-contributed libraries or wrappers might exist for various programming languages that abstract away the HTTP request and encoding complexities. Searching for 'Kroki client library' on package managers for your language (e.g., npm for Node.js, PyPI for Python) can reveal useful tools.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting tips:
- HTTP Status Codes:
400 Bad Request: This often indicates an issue with your diagram syntax or the request payload. Double-check the diagram code for errors and ensure it's correctly base64-encoded. Verify that theContent-Typeheader istext/plain.404 Not Found: This usually means the endpoint URL is incorrect. Confirm that the diagram type (e.g.,mermaid) and output format (e.g.,svg) are spelled correctly and supported by Kroki Kroki HTTP API reference.500 Internal Server Error: This suggests an issue on the Kroki server side. While rare for the public instance, it can happen with self-hosted instances if a diagramming tool is misconfigured or if there's a resource issue.
- Diagram Syntax Errors:
Many diagramming tools are sensitive to syntax. If you receive an image with an error message or no image at all, try testing your diagram code in a dedicated online editor for that tool (e.g., Mermaid Live Editor, PlantUML Online Server) to confirm it's valid before sending it to Kroki. The Kroki API response might also contain error details in the image itself or in an error message if the output format supports it.
- Encoding Issues:
Ensure your diagram code is correctly compressed with zlib (
deflateRaw) and then base64-encoded. Incorrect encoding can lead to unreadable payloads for Kroki. The base64 encoding used by Kroki is URL-safe, meaning+characters are replaced with-and/with_. If you're manually encoding, ensure these replacements are made Kroki encoding guidance. - Content-Type Header:
Always set the
Content-Typeheader totext/plainwhen making a POST request to Kroki. Sending an incorrect content type can cause Kroki to misinterpret the request body. - Network Connectivity:
Verify that your environment has outbound network access to
https://kroki.io. Firewall rules or proxy settings might block the request. - Check Kroki Server Logs (Self-Hosted):
If you are using a self-hosted Kroki instance, consult the server logs. These logs often provide detailed error messages that can pinpoint the exact cause of a rendering failure, such as missing diagramming tools or configuration issues.