API Reference for Java

The Scalar Java integration provides an easy way to render beautiful API References based on OpenAPI documents in Java applications.

Module Architecture

The Scalar Java integration consists of 3 separate modules:

  • scalar-core - Framework-agnostic core module with no dependencies (except Jackson for JSON serialization). Can be used anywhere to display an API Reference.
  • scalar-webmvc - Spring Boot WebMVC integration module
  • scalar-webflux - Spring Boot WebFlux integration module

Breaking Change: Previously, there was only a single scalar module that was compatible with Spring Boot MVC. The integration has been restructured into 3 separate modules to support both WebMVC and WebFlux, and to provide a framework-agnostic core module.

Migration: If you were using the old scalar module, replace it with scalar-webmvc for Spring Boot WebMVC applications. See the Migration Guide below for details.

Migration Guide

If you were using the previous single scalar module, follow these steps to migrate:

Step 1: Update Dependencies

Maven:

<!-- Remove the old dependency -->
<!-- <dependency>
  <groupId>com.scalar.maven</groupId>
  <artifactId>scalar</artifactId>
  <version>X.X.X</version>
</dependency> -->

<!-- Add the new WebMVC module -->
<dependency>
  <groupId>com.scalar.maven</groupId>
  <artifactId>scalar-webmvc</artifactId>
  <version>X.X.X</version>
</dependency>

Gradle:

// Remove the old dependency
// implementation 'com.scalar.maven:scalar:X.X.X'

// Add the new WebMVC module
implementation 'com.scalar.maven:scalar-webmvc:X.X.X'

Step 2: Configuration

Your existing configuration in application.properties or application.yml remains the same. The property names and structure are unchanged.

Step 3: Custom Controllers (if applicable)

If you had custom controller implementations, you'll need to update them to extend ScalarWebMvcController instead of the old controller class. See the Custom Controllers section below.

Basic Setup

Spring Boot WebMVC

  1. Add the dependency

Maven:

<dependency>
  <groupId>com.scalar.maven</groupId>
  <artifactId>scalar-webmvc</artifactId>
  <version>X.X.X</version>
</dependency>

Gradle:

implementation 'com.scalar.maven:scalar-webmvc:X.X.X'
  1. Configure your application

Add the following to your application.properties:

scalar.enabled=true
scalar.url=https://example.com/openapi.json

Or in application.yml:

scalar:
  enabled: true
  url: https://example.com/openapi.json
  1. Access the API Reference

Navigate to /scalar (or your custom path) to view your API Reference.

Spring Boot WebFlux

  1. Add the dependency

Maven:

<dependency>
  <groupId>com.scalar.maven</groupId>
  <artifactId>scalar-webflux</artifactId>
  <version>X.X.X</version>
</dependency>

Gradle:

implementation 'com.scalar.maven:scalar-webflux:X.X.X'
  1. Configure your application

Add the following to your application.properties:

scalar.enabled=true
scalar.url=https://example.com/openapi.json

Or in application.yml:

scalar:
  enabled: true
  url: https://example.com/openapi.json
  1. Access the API Reference

Navigate to /scalar (or your custom path) to view your API Reference.

Configuration Options

The Scalar integration can be configured via Spring Boot properties. All configuration properties use the scalar prefix.

Basic Configuration

# Enable/disable Scalar (default: true)
scalar.enabled=true

# OpenAPI specification URL
scalar.url=https://api.example.com/openapi.json

# Custom path for the API Reference (default: /scalar)
scalar.path=/docs

# Page title (default: "API Reference")
scalar.pageTitle=My API Documentation

Additional UI and Client Options

These options work in both WebMVC and WebFlux. Omitted values use the frontend defaults.

Spring property Values
scalar.show-badges-in-sidebar Show x-badges next to sidebar titles (default: false)
scalar.hide-model-names true or false
scalar.schema-keyboard-nav true or false
scalar.expand-all-parameters true or false
scalar.max-visible-request-body-properties Nonnegative integer; 0 shows all
scalar.default-request-body-view form or raw
scalar.show-extensions List of extension keys such as x-internal
scalar.featured-clients Ordered list of full client IDs such as node/fetch
scalar.show-default-clients-with-sdk-installation Show built-in HTTP clients alongside SDK installation tabs (default: false)
scalar.url-routing false leaves the browser URL and history unchanged
scalar.oauth2-redirect-uri Default OAuth redirect URI
scalar.agent.hide-add-api Hide the agent's control for adding APIs; also available under each source

Override individual service URLs with scalar.external-urls.dashboard-url, registry-url, proxy-url, and api-base-url. Unset URLs retain their defaults.

For hidden clients, choose exactly one of all, clients, or targets:

scalar:
  hidden-clients:
    targets:
      python:
        all: true
      node:
        clients: [fetch]
  featured-clients: [shell/curl, node/axios]

Use scalar.hidden-clients.all=true to hide every client. Set it to false, or set clients: [], to show all clients, including clients hidden by default. The clients list accepts target names, client names, and full client IDs. Each target entry accepts either all or clients; target entries cannot contain more targets.

The Java API uses ScalarHiddenClients and ScalarExternalUrls for the same options. These are serialized into the frontend's native configuration shapes.

Path-Based Navigation

By default, navigation uses URL fragments. To use paths and support direct visits or reloads of nested documentation URLs:

scalar.path=/docs
scalar.path-routing.base-path=/docs

Both WebMVC and WebFlux register a GET fallback for the configured documentation subtree for requests that explicitly accept text/html. Wildcard requests from scripts, styles, images, and fetch() continue to reach static resource handlers, including when the base path is /. Existing exact application routes and the JavaScript bundle keep precedence. The base path may differ from scalar.path; the bundle remains served under scalar.path. Avoid choosing a subtree owned by unrelated application routes.

base-path is a literal path relative to the application, without its context path. For example, with server.servlet.context-path=/app, configure /docs, not /app/docs. The rendered frontend configuration and bundle URL include /app. For WebFlux, the same applies to its application context path. Configure trusted forwarded-header handling in the host application when a reverse proxy adds a prefix.

Trailing slashes on the routing base path are normalized. Setting scalar.url-routing=false leaves browser history unchanged and disables automatic deep-link fallback registration. With no path-routing configuration, existing hash navigation and server mappings are unchanged.

Route registration happens at startup. Set the base path through application configuration or the properties bean, rather than changing it per request. The Actuator page uses hash navigation and its existing relative bundle URL even when path routing is configured for the main documentation endpoint.

Localization

Both WebMVC and WebFlux support UI localization through Spring Boot properties. For example, use Simplified Chinese:

scalar.localization.locale=zh-CN

Text direction accepts auto, ltr, or rtl; invalid values fail during Spring Boot configuration binding.

You can also set text direction and override individual UI translations in application.yml:

scalar:
  localization:
    locale: zh-CN
    direction: auto
    translations:
      search:
        label: 搜索
      operation:
        testRequest: 发送请求

Translation overrides are merged with the built-in locale and English fallback. When localization is omitted, the UI uses English.

Inline API Descriptions and Document Identity

Use content for a JSON or YAML string, or content-map for a Spring-bound object. Both forms are available globally and under each sources entry. Inline content takes precedence over a URL, including the default sample URL. Global content also takes precedence over per-source url values because the frontend copies global fields onto every source. To display different documents, set content or a URL on each source and leave global content unset. Use only one content form at a time.

scalar:
  title: Internal API
  slug: internal
  page-title: Developer Portal
  content: |
    openapi: 3.1.2
    info:
      title: Internal API
      version: '1'
    paths: {}

title and slug identify the document. page-title controls the HTML page title.

Prefer the text form for Spring configuration: YAML property flattening drops empty maps such as paths: {}, and binding can change JSON/YAML value types or special map keys. content-map remains available when these limitations are acceptable. Programmatic Java callers can use setContent(String) or pass a Map<String, Object> to setContent(Object).

Selected client persistence

The selected code sample client is saved in local storage by default. Disable saving and restoring it with:

scalar.persistSelectedClient=false

For programmatic configuration, call properties.setPersistSelectedClient(false). This applies to both Spring MVC and WebFlux. Client selection still works for the current page, and persistAuth is controlled separately.

Authentication Alternatives

scalar.authentication.create-any-security-scheme=true allows users to add authentication schemes that are not declared in the API description.

The existing preferred-security-schemes flat list still selects alternatives. For schemes that must be used together, use preferred-security-scheme-groups:

scalar:
  authentication:
    preferred-security-scheme-groups:
      - [apiKey, bearer]
      - [oauth]

This represents (apiKey AND bearer) OR oauth. Choose either the flat list or groups. The Java setters setPreferredSecurityScheme(String) and setPreferredSecuritySchemes(List<String>) remain available; setPreferredSecuritySchemeGroups(List<List<String>>) adds grouped alternatives. Setting one form replaces the other. The legacy flat-list getter returns null when grouped preferences are configured.

Multiple OpenAPI Documents

You can configure multiple OpenAPI documents using the sources property:

scalar:
  enabled: true
  sources:
    - url: https://api.example.com/v1/openapi.json
      title: Production API
      slug: v1
      isDefault: true
    - url: https://api.example.com/v2/openapi.json
      title: Beta API
      slug: v2

Or in application.properties:

scalar.sources[0].url=https://api.example.com/v1/openapi.json
scalar.sources[0].title=Production API
scalar.sources[0].slug=v1
scalar.sources[0].isDefault=true

scalar.sources[1].url=https://api.example.com/v2/openapi.json
scalar.sources[1].title=Beta API
scalar.sources[1].slug=v2

UI Customization

# Theme (default, moon, purple, solarized, bluePlanet, saturn, kepler, mars, deepSpace, laserwave, alternate, none)
scalar.theme=moon

# Layout (modern, classic)
scalar.layout=modern

# Show/hide sidebar (default: true)
scalar.showSidebar=true

# Hide models from sidebar and search (default: false)
scalar.hideModels=false

# Hide test request button (default: false)
scalar.hideTestRequestButton=false

# Dark mode (default: false)
scalar.darkMode=true

# Hide dark mode toggle (default: false)
scalar.hideDarkModeToggle=false

# Hide search bar (default: false)
scalar.hideSearch=false

# Custom CSS
scalar.customCss=body { background: #f0f0f0; }

Server Configuration

Override or add servers for the API Reference:

scalar:
  servers:
    - url: https://api.example.com
      description: Production Server
    - url: https://staging-api.example.com
      description: Staging Server

Proxy Configuration

Configure a proxy URL for API requests:

scalar.proxyUrl=https://api-gateway.company.com

Agent

Agent adds an AI chat interface to your API reference. Users can ask questions about your API and get contextual answers based on your OpenAPI document.

  • Enabled by default on http://localhost for testing (with limited free messages).
  • In production, the agent does not appear unless you provide a key.
  • To use Agent in production, configure an Agent key.

Single-URL mode (when using scalar.url without sources):

scalar:
  url: https://api.example.com/openapi.json
  agent:
    key: put-your-agent-scalar-key-here

To disable Agent entirely in single-URL mode:

scalar:
  agent:
    disabled: true

Multiple OpenAPI documents (when using sources): set agent options per source:

scalar:
  sources:
    - url: https://api.example.com/v1/openapi.json
      title: Production API
      agent:
        key: put-your-agent-scalar-key-here
    - url: https://api.example.com/v2/openapi.json
      title: Beta API
      agent:
        disabled: true

In application.properties for a single source:

scalar.agent.key=put-your-agent-scalar-key-here
# Or to disable:
scalar.agent.disabled=true

For multiple sources:

scalar.sources[0].agent.key=put-your-agent-scalar-key-here
scalar.sources[1].agent.disabled=true

Related: How to get an Agent key.

Authentication

Scalar allows you to pre-configure authentication details for your API, making it easier for developers to test your endpoints.

Before you start: Your OpenAPI document must already include authentication security schemes for Scalar to work with them. Scalar can only pre-fill authentication details for schemes that are already defined in your OpenAPI specification.

Security Notice: Pre-filled authentication details are visible in the browser and should never be used in production environments. Only use this feature for development and testing.

API Key Authentication

scalar:
  authentication:
    preferredSecurityScheme: ApiKey
    apiKey:
      ApiKey:
        name: X-API-Key
        value: sk-demo-key-12345

Bearer Token Authentication

scalar:
  authentication:
    preferredSecurityScheme: BearerAuth
    http:
      BearerAuth:
        token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Basic Authentication

scalar:
  authentication:
    preferredSecurityScheme: BasicAuth
    http:
      BasicAuth:
        username: demo-user
        password: demo-password

OAuth2 Authentication

Scalar provides support for all OAuth2 flow types. Configure them in the flows section of your OAuth2 security scheme.

Authorization Code Flow
scalar:
  authentication:
    preferredSecurityScheme: OAuth2
    oauth2:
      OAuth2:
        flows:
          authorizationCode:
            clientId: scalar-demo-client
            clientSecret: scalar-demo-secret
            authorizationUrl: https://auth.example.com/oauth2/authorize
            tokenUrl: https://auth.example.com/oauth2/token
            pkce: sha256
            selectedScopes:
              - read
              - write
              - admin
        defaultScopes:
          - read
          - write
Client Credentials Flow
scalar:
  authentication:
    preferredSecurityScheme: OAuth2
    oauth2:
      OAuth2:
        flows:
          clientCredentials:
            clientId: service-client-12345
            clientSecret: service-secret-67890
            tokenUrl: https://auth.example.com/oauth2/token
            selectedScopes:
              - api.read
              - api.write
Password Flow
scalar:
  authentication:
    preferredSecurityScheme: OAuth2
    oauth2:
      OAuth2:
        flows:
          password:
            clientId: password-client
            clientSecret: password-secret
            tokenUrl: https://auth.example.com/oauth2/token
            username: demo@example.com
            password: demo-password-123
            selectedScopes:
              - profile
              - email
Implicit Flow
scalar:
  authentication:
    preferredSecurityScheme: OAuth2
    oauth2:
      OAuth2:
        flows:
          implicit:
            clientId: spa-client-abc123
            authorizationUrl: https://auth.example.com/oauth2/authorize
            selectedScopes:
              - openid
              - profile
              - email
Multiple OAuth2 Flows

You can configure multiple flows for the same OAuth2 security scheme:

scalar:
  authentication:
    preferredSecurityScheme: OAuth2
    oauth2:
      OAuth2:
        flows:
          authorizationCode:
            clientId: web-client-12345
            authorizationUrl: https://auth.example.com/oauth2/authorize
            tokenUrl: https://auth.example.com/oauth2/token
          clientCredentials:
            clientId: service-client-67890
            clientSecret: service-secret
            tokenUrl: https://auth.example.com/oauth2/token
        defaultScopes:
          - read
          - write

Advanced Configuration

# Default HTTP client for code samples (default: shell/curl)
scalar.defaultHttpClient.target=shell
scalar.defaultHttpClient.client=curl

# Expand all tags by default (default: false)
scalar.defaultOpenAllTags=true

# Expand all model sections (default: false)
scalar.expandAllModelSections=true

# Expand all response sections (default: false)
scalar.expandAllResponses=true

# Base server URL to prefix relative OpenAPI server URLs
scalar.baseServerUrl=https://api.example.com

# Persist authentication in local storage (default: false)
scalar.persistAuth=true

# Enable telemetry (default: true)
scalar.telemetry=false

# Order required properties first (default: true)
scalar.orderRequiredPropertiesFirst=true

# Show operation ID (default: false)
scalar.showOperationId=true

# Hide client button (default: false)
scalar.hideClientButton=false

# Favicon path
scalar.favicon=favicon.svg

# Use default fonts (Inter and JetBrains Mono from CDN) (default: true)
scalar.withDefaultFonts=true

Custom Controllers

Both ScalarWebMvcController and ScalarWebFluxController can be extended to customize behavior. The controllers use @ConditionalOnMissingBean, so you can provide your own implementation.

WebMVC Custom Controller

import com.scalar.maven.webmvc.ScalarWebMvcController;
import com.scalar.maven.core.ScalarProperties;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomScalarController extends ScalarWebMvcController {

    @Override
    protected ScalarProperties configureProperties(
            ScalarProperties properties,
            HttpServletRequest request) {
        // Customize properties based on request
        if (request.isUserInRole("ADMIN")) {
            properties.setPageTitle("Admin API Documentation");
        }

        // Modify other properties as needed
        properties.setDarkMode(true);

        return properties;
    }
}

WebFlux Custom Controller

import com.scalar.maven.webflux.ScalarWebFluxController;
import com.scalar.maven.core.ScalarProperties;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomScalarController extends ScalarWebFluxController {

    @Override
    protected ScalarProperties configureProperties(
            ScalarProperties properties,
            ServerHttpRequest request) {
        // Customize properties based on request
        String path = request.getPath().value();
        if (path.contains("/admin")) {
            properties.setPageTitle("Admin API Documentation");
        }

        // Modify other properties as needed
        properties.setDarkMode(true);

        return properties;
    }
}

The configureProperties method is called before the ScalarProperties are serialized to JSON and rendered. This allows you to dynamically modify the configuration based on the incoming request. Each request receives a fresh instance of ScalarProperties, so you can safely modify it without affecting other concurrent requests.

Actuator Support

Scalar can be exposed as a Spring Boot Actuator endpoint. This is useful for production environments where you want to expose the API Reference through the actuator management endpoints.

Enable Actuator Endpoint

# Enable actuator endpoint
scalar.actuatorEnabled=true

# Configure actuator exposure (if using Spring Boot Actuator)
management.endpoints.web.exposure.include=scalar,health

The Scalar UI will be available at /actuator/scalar when actuator is enabled.

Using scalar-core Standalone

The scalar-core module is framework-agnostic and can be used in any Java application, not just Spring Boot. It has no framework dependencies (only Jackson for JSON serialization).

Maven Dependency

<dependency>
  <groupId>com.scalar.maven</groupId>
  <artifactId>scalar-core</artifactId>
  <version>X.X.X</version>
</dependency>

Gradle Dependency

implementation 'com.scalar.maven:scalar-core:X.X.X'

Usage Example

import com.scalar.maven.core.ScalarProperties;
import com.scalar.maven.core.ScalarHtmlRenderer;

// Create and configure properties
ScalarProperties properties = new ScalarProperties();
properties.setUrl("https://api.example.com/openapi.json");
properties.setPath("/docs");
properties.setPageTitle("My API Documentation");
properties.setTheme(ScalarTheme.MOON);
properties.setLayout(ScalarLayout.MODERN);

// Render HTML
String html = ScalarHtmlRenderer.render(properties);

// Serve the HTML in your application
// (e.g., via a servlet, JAX-RS endpoint, etc.)

You can then serve the rendered HTML through any HTTP framework or servlet container of your choice.

Additional Information

For all available configuration properties and their default values, check out the ScalarProperties class.

The Scalar Java integration requires Java 17 or higher and is compatible with Spring Boot 3.x.

What did you think of this content?