Apache Axis2 OpenAPI REST Services User's Guide

What is OpenAPI? OpenAPI (formerly known as Swagger) is an industry-standard specification for describing REST APIs. It provides a machine-readable format that precisely defines your API endpoints, request/response schemas, authentication methods, and error handling. Think of it as a contract that documents exactly how your REST API behaves, enabling automatic client code generation, interactive testing, and comprehensive documentation that stays in sync with your actual implementation.

Why use OpenAPI? For developers, OpenAPI eliminates the tedious manual work of writing and maintaining API documentation, reduces integration errors through precise specifications, and enables powerful tooling ecosystems. Your frontend developers get auto-generated TypeScript clients, your QA teams get interactive testing interfaces via Swagger UI, and your DevOps teams can generate monitoring configurations automatically. Most importantly, OpenAPI specifications serve as the single source of truth for your API, preventing the documentation drift that plagues many projects.

This guide demonstrates how to create OpenAPI 3.0.1 documented REST services with Apache Axis2, providing a drop-in replacement solution for existing REST backends. It includes comprehensive examples for financial services, data management systems, and enterprise applications with OpenAPI specification support and interactive Swagger UI documentation!

The guide shows how to build REST services that can seamlessly replace existing backends (Spring Boot, Express.js, etc.) while maintaining API compatibility for frontend applications such as Excel Add-ins, React apps, and TypeScript clients.

Introduced in Axis2 2.0.1: OpenAPI 3.0.1 integration with automatic specification generation from deployed services, Swagger UI support, and an MCP tool catalog.

More documentation about Axis2 REST support can be found in the Pure JSON Support documentation and JSON User Guide. For modern enterprise features including Bearer authentication, advanced security schemes, and comprehensive configuration options, see the OpenAPI Advanced User Guide.

Introduction

This user guide is written based on the Axis2 Standard Binary Distribution. The Standard Binary Distribution can be directly downloaded or built using the Source Distribution. If you choose the latter, then the Installation Guide will instruct you on how to build Axis2 Standard Binary Distribution using the source.

The source code for this guide is a small sample application demonstrating an OpenAPI-documented REST authentication service. The data, calculation and Excel examples later in this guide are illustrative patterns for your own services; they are not part of the sample.

Please note that Axis2 is an open-source effort. If you feel the code could use some new features or fixes, please get involved and lend us a hand! The Axis developer community welcomes your participation.

Let us know what you think! Send your feedback to "java-user@axis.apache.org". (Subscription details are available on the Axis2 site.) Kindly prefix the subject of the mail with [Axis2].

OpenAPI Integration Features

Since 2.0.1, Axis2 provides OpenAPI 3.0.1 integration designed for enterprise REST services and drop-in backend replacement scenarios. The OpenAPI module generates the specification from the services deployed in Axis2, and lets you adjust the generated document programmatically.

Key OpenAPI Features

  • Automatic Generation: The specification is generated by introspecting the deployed Axis2 services; an OpenApiCustomizer can modify the generated document
  • Interactive Documentation: Swagger UI (served at /swagger-ui) for API testing and exploration
  • Standard Endpoints: OpenAPI specifications served at /openapi.json and /openapi.yaml, and an MCP tool catalog at /openapi-mcp.json
  • CORS Headers: The specification and Swagger UI responses carry permissive CORS headers for browser-based tools
  • Service Discovery: Automatic detection of REST-enabled Axis2 services
  • Drop-in Compatibility: Designed to replace existing REST backends without frontend changes

Customizing the Generated Specification

The OpenAPI module always generates the specification from the deployed services; it does not serve a hand-written schema file in place of the generated one. To change the generated document (add servers, security schemes, descriptions or extra schemas), implement org.apache.axis2.openapi.OpenApiCustomizer and register it on the OpenApiConfiguration. See the OpenAPI Advanced User Guide for details.

Drop-in Backend Replacement

The Axis2 OpenAPI integration is specifically designed for backend replacement scenarios:

  • API Compatibility: Maintain existing endpoint paths, request/response formats
  • Authentication Patterns: Support for custom headers and standard Bearer tokens
  • Frontend Support: Compatible with TypeScript clients, Excel Add-ins, React apps
  • Migration Path: Gradual service-by-service replacement without breaking changes

Getting Started

This user guide explains how to write and deploy OpenAPI-documented REST services using Axis2, and how to replace existing backends while maintaining frontend compatibility.

All the sample code mentioned in this guide is located in the "modules/samples/swagger-server" directory of Axis2 standard binary distribution.

The sample provides an OpenAPI-documented authentication service, together with a reference OpenAPI contract for a larger financial API (src/main/resources/openapi/financial-api-schema.json).

Testing the Sample: The swagger-server sample includes comprehensive unit tests for all service components and models. To run the tests, navigate to the sample directory and execute mvn test. The test suite covers authentication flows, data validation, JSON serialization/deserialization, and service method functionality. Individual test classes can be found in src/test/java/org/apache/axis2/samples/swagger and provide excellent examples of how to test REST services with custom authentication patterns and complex data models.

Creating OpenAPI REST Services

The guide demonstrates how to create secure, OpenAPI-documented REST services using real-world patterns commonly found in financial services and data management applications.

Sample Services Overview

The swagger-server sample contains one service:

  • AuthenticationService: POST /bigdataservice/login, login with custom token generation. For demonstration it accepts any well-formed email address with the credentials demo.

The reference contract financial-api-schema.json also describes /bigdataservice/funds/summary, /bigdataservice/assets/calculate and /bigdataservice/user/*; these are not implemented by the sample. The data, calculation and Excel services shown below are illustrative patterns for your own services.

Authentication Service

The AuthenticationService demonstrates token-based authentication using OpenAPI 3.x annotations (from io.swagger.v3.oas.annotations):

@Path("/bigdataservice")
@Tag(name = "authentication", description = "User authentication and token management")
public class AuthenticationService {

    @POST
    @Path("/login")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Operation(summary = "User authentication",
               description = "Authenticate user with email and password, returns JWT token on success")
    public Response authenticateUser(LoginRequest loginRequest) {
        // Token generation and validation logic
    }
}

Data Service

An illustrative data service with authenticated endpoints (not part of the sample):

@Path("/api/data")
@Tag(name = "data", description = "Data management operations")
public class DataService {

    @POST
    @Path("/query")
    @Operation(summary = "Query dataset",
               description = "Retrieve filtered data with pagination")
    public QueryResponse query(
            @Parameter(description = "Query parameters") QueryRequest request,
            @HeaderParam("Authorization") String bearerToken) {
        // Data processing logic
    }

    @POST
    @Path("/calculate")
    @Operation(summary = "Run calculation")
    public CalculationResponse calculate(
            CalculationRequest request,
            @HeaderParam("Authorization") String bearerToken) {
        // Calculation logic
    }
}

Note: Axis2's OpenAPI integration uses io.swagger.v3.oas.annotations (OpenAPI 3.x), not the older Swagger 1.x annotations (@Api, @ApiOperation, @ApiParam). See the Swagger 2.x annotation guide for the full reference.

Request/Response Models

Axis2 supports multiple JSON libraries — Moshi, Gson, and a streaming formatter — each with standard and HTTP/2-enhanced variants. Select the library by choosing the corresponding message builder and formatter classes in axis2.xml. The examples below use Moshi's @Json annotation; Gson provides equivalent functionality with @SerializedName:

public class LoginRequest {
    @Json(name = "email")
    private String email;

    @Json(name = "credentials")
    private String credentials;

    // Getters and setters
}

public class LoginResponse {
    @Json(name = "data")
    private LoginData data;

    @Json(name = "errorMessage")
    private String errorMessage;

    // Compatible with existing frontend expectations
}

OpenAPI Module Configuration

To enable OpenAPI documentation, place the openapi module archive (openapi-<version>.mar, built from axis2-openapi) in the repository's modules directory and engage it in your axis2.xml:

<module ref="openapi" />

The module generates the specification, but it does not register any servlet itself. The documentation endpoints are served by delegating to the module's SwaggerUIHandler from a servlet mapped at /openapi.json, /openapi.yaml, /swagger-ui and /openapi-mcp.json. The Axis2 Spring Boot Starter registers such a servlet automatically; the springbootdemo-tomcat11 sample shows a hand-written OpenApiServlet that calls OpenApiModule.getSwaggerUIHandler(configContext).

OpenAPI Configuration Parameters

Configuration is read from an openapi.properties file on the classpath, and any of the same keys may be overridden with Java system properties (for example -Dopenapi.title=...). The supported keys are:

  • openapi.title, openapi.description, openapi.version, openapi.termsOfServiceUrl: API information in the generated specification
  • openapi.contact.name, openapi.contact.email, openapi.contact.url: contact information
  • openapi.license.name, openapi.license.url: license information
  • openapi.serverBaseUrl: absolute URL to publish in servers[].url; by default a relative URL is published rather than one derived from the request
  • openapi.prettyPrint: pretty-print the generated JSON
  • openapi.swaggerUi.enabled: enable the Swagger UI page (default: true)
  • openapi.swaggerUi.version, openapi.swaggerUi.integrity.bundle, openapi.swaggerUi.integrity.standalonePreset: the Swagger UI version loaded from the CDN (default 5.32.13) and the Subresource Integrity hashes for a non-default version
  • openapi.resourcePackages, openapi.readAllResources: which resource classes to scan
  • openapi.ignoredServices, openapi.ignoredOperations, openapi.ignoredRoutes: comma-separated services, operations (ServiceName/opName or opName) and path patterns to leave out of the specification

The module.xml inside the .mar also accepts the parameters title, version, description, prettyPrint, supportSwaggerUi and propertiesFile (the name of an additional properties file to load).

Client Usage and API Compatibility

The OpenAPI REST services are designed for seamless integration with existing frontend applications. Here are examples showing drop-in compatibility patterns:

Authentication - Custom Token Pattern

Login request maintaining existing frontend patterns:

curl -v -H "Content-Type: application/json" \
     -X POST \
     --data '{"email":"user@company.com","credentials":"demo"}' \
     http://localhost:8080/axis2/services/authService/login

Response format compatible with existing frontends:

{
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "userId": "user123",
    "email": "user@company.com"
  },
  "errorMessage": null
}

Data Services - Custom Header Authentication

Data requests using a custom bigdataToken header (maintaining frontend compatibility). This and the following examples illustrate patterns for your own services; the sample does not implement them:

curl -v -H "bigdataToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
     -H "Content-Type: application/json" \
     -X POST \
     --data '{"marketId":"MKT001","includeHistory":true}' \
     http://localhost:8080/axis2/services/dataService/marketSummary

Where the response maintains existing data structure:

{
  "data": {
    "marketId": "MKT001",
    "marketName": "Growth Market",
    "totalValue": 1500000.00,
    "performanceData": {
      "ytdReturn": 12.5,
      "annualizedReturn": 8.2
    }
  },
  "errorMessage": null
}

Financial Calculation Services

Financial calculation requests with custom authentication:

curl -v -H "bigdataToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
     -H "Content-Type: application/json" \
     -X POST \
     --data '{"calculationType":"netPresentValue","cashFlows":[100,200,300],"discountRate":0.05}' \
     http://localhost:8080/axis2/services/dataService/financialCalculation

Financial calculation response format:

{
  "data": {
    "calculationType": "netPresentValue",
    "result": 544.22,
    "calculationDetails": {
      "inputCashFlows": [100, 200, 300],
      "discountRate": 0.05,
      "periodCount": 3
    }
  },
  "errorMessage": null
}

Excel Integration - Function Metadata

Excel Add-in compatibility with function specification endpoints:

curl -v -H "bigdataToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
     -H "Content-Type: application/json" \
     -X GET \
     http://localhost:8080/axis2/services/excelService/functionSpecs

Response providing Excel function metadata:

{
  "data": {
    "functions": [
      {
        "name": "MARKET_VALUE",
        "description": "Get current market value",
        "parameters": ["marketId", "asOfDate"],
        "returnType": "number"
      },
      {
        "name": "FINANCIAL_CALC",
        "description": "Perform financial calculations",
        "parameters": ["calculationType", "parameters"],
        "returnType": "number"
      }
    ]
  },
  "errorMessage": null
}

OpenAPI Documentation Access

Once deployed, the OpenAPI integration provides multiple ways to access API documentation:

Interactive Swagger UI

Access the interactive API documentation at the path where the OpenAPI servlet is mapped, for example:

http://localhost:8080/axis2/swagger-ui

The Swagger UI provides:

  • Interactive Testing: Try API endpoints directly from the browser
  • Authentication Support: Test with custom headers and tokens
  • Request/Response Examples: See expected data formats
  • Schema Documentation: Detailed model and parameter information

OpenAPI Specification Endpoints

Access the raw OpenAPI specifications:

# JSON format
http://localhost:8080/axis2/openapi.json

# YAML format
http://localhost:8080/axis2/openapi.yaml

# MCP tool catalog
http://localhost:8080/axis2/openapi-mcp.json

The specification endpoints send CORS headers for frontend integration and can be used by:

  • Code Generation: Generate TypeScript/JavaScript clients
  • API Testing: Import into Postman, Insomnia, or similar tools
  • Documentation: Generate static documentation or integrate with docs systems

Drop-in Replacement Guide

This section provides step-by-step guidance for replacing existing REST backends with Axis2 OpenAPI services while maintaining frontend compatibility.

Migration Strategy

Follow this approach for seamless backend replacement:

  1. API Analysis: Document existing endpoints, request/response formats, and authentication patterns
  2. Service Implementation: Create Axis2 services matching existing API contracts
  3. Configuration: Engage the OpenAPI module and compare the generated specification with your existing schema, adjusting it with an OpenApiCustomizer where needed
  4. Testing: Validate compatibility with existing frontend applications
  5. Deployment: Replace backend services incrementally

Common Compatibility Patterns

Handle common frontend integration patterns:

Custom Authentication Headers

// Support existing custom headers instead of standard Authorization
@HeaderParam("bigdataToken") String customToken
@HeaderParam("apiKey") String apiKey
@HeaderParam("sessionId") String sessionId

Response Envelope Patterns

// Many frontends expect data/error envelope pattern
public class StandardResponse<T> {
    @Json(name = "data")
    private T data;

    @Json(name = "errorMessage")
    private String errorMessage;

    @Json(name = "success")
    private boolean success = true;
}

Path Parameter Compatibility

// Match existing URL patterns exactly
@Path("/api/v1/markets/{marketId}/summary")
@Path("/bigdataservice/calculate")  // Legacy path support
@Path("/excel/functions/{functionName}")

Frontend Integration Testing

Validate drop-in compatibility with these testing approaches:

  • TypeScript Clients: Ensure generated clients work without modifications
  • Excel Add-ins: Test Office.js integrations and custom function calls
  • React/Angular Apps: Verify existing HTTP service layers continue working
  • Mobile Apps: Test native HTTP clients and authentication flows

Configuration for Different Frameworks

Axis2 OpenAPI services can replace backends built with various frameworks:

Spring Boot Replacement

# Spring Boot endpoint:
@PostMapping("/api/markets/summary")
public ResponseEntity<MarketResponse> getMarketSummary(@RequestBody MarketRequest request)

# Equivalent Axis2 service:
@POST
@Path("/api/markets/summary")
public MarketResponse getMarketSummary(MarketRequest request)

Express.js/Node.js Replacement

// Express.js endpoint:
app.post('/api/auth/login', (req, res) => { ... })

// Equivalent Axis2 service:
@POST
@Path("/api/auth/login")
public LoginResponse login(LoginRequest request)

ASP.NET Core Replacement

// ASP.NET Core endpoint:
[HttpPost("/api/data/process")]
public ActionResult<DataResponse> ProcessData([FromBody] DataRequest request)

// Equivalent Axis2 service:
@POST
@Path("/api/data/process")
public DataResponse processData(DataRequest request)

Performance and Best Practices

The Axis2 OpenAPI integration is designed for enterprise performance and scalability:

Performance Optimizations

  • JSON Processing: Choice of Moshi, Gson, or streaming formatters — each with HTTP/2-enhanced variants for large payloads
  • HTTP Caching: Specification responses carry a short Cache-Control max-age, and static Swagger UI resources a longer one
  • Memory Management: Streaming support for large request/response payloads

Best Practices

  • Schema Validation: Use OpenAPI schema validation for request/response verification
  • Error Handling: Implement consistent error response formats across all services
  • Authentication: Centralize token validation and user context management
  • Monitoring: Implement service health checks and performance metrics
  • Documentation: Keep OpenAPI schemas up-to-date with service changes

Security Considerations

Ensure secure REST API implementation:

  • Input Validation: Validate all request parameters and payloads
  • Authentication: Implement proper token validation and session management
  • CORS Policy: Configure appropriate CORS policies for production environments
  • HTTPS: Use HTTPS in production for secure data transmission
  • Rate Limiting: Implement rate limiting to prevent API abuse

Troubleshooting and Support

Common issues and solutions when implementing OpenAPI REST services:

Module Loading Issues

If the OpenAPI module fails to load:

  1. Verify the module is included in axis2.xml: <module ref="openapi" />
  2. Check that the openapi .mar file is present in the modules directory
  3. Review server logs for initialization errors

Swagger UI Access Problems

If Swagger UI is not accessible:

  1. Confirm openapi.swaggerUi.enabled is not set to false
  2. Check that a servlet delegating to SwaggerUIHandler is mapped at /swagger-ui
  3. If the page loads but stays blank, check that the browser can reach the Swagger UI CDN

API Compatibility Issues

When replacing existing backends:

  1. Compare request/response formats using API testing tools
  2. Verify custom header handling and authentication patterns
  3. Test with actual frontend applications, not just cURL
  4. Review error response formats and status codes

Performance Issues

For performance optimization:

  1. Monitor memory usage with large JSON payloads
  2. Profile JSON serialization/deserialization performance
  3. Check database connection pooling and query optimization

For additional support, contact the Axis2 community through the mailing lists or GitHub issues. The community welcomes contributions and feedback on the OpenAPI integration.