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.

New in Axis2 2.0.1: Complete OpenAPI 3.0.1 integration with automatic specification generation, Swagger UI support, and flexible generation modes (AUTOMATIC/STATIC/HYBRID) designed for real-world enterprise usage patterns.

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 provides a complete sample application demonstrating OpenAPI REST services with financial data management capabilities, including authentication, data processing, and Excel integration patterns.

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

Axis2 2.0.1 provides comprehensive OpenAPI 3.0.1 integration designed for enterprise REST services and drop-in backend replacement scenarios. The OpenAPI module offers flexible generation modes to balance automatic documentation with real-world usage patterns.

Key OpenAPI Features

  • Multiple Generation Modes: AUTOMATIC (service introspection), STATIC (manual schemas), and HYBRID (base generation with static overrides)
  • Interactive Documentation: Built-in Swagger UI at /swagger-ui endpoint for API testing and exploration
  • Standard Endpoints: OpenAPI specifications served at /openapi.json and /openapi.yaml
  • CORS Support: Enabled by default for browser-based testing and frontend integration
  • Service Discovery: Automatic detection of REST-enabled Axis2 services
  • Drop-in Compatibility: Designed to replace existing REST backends without frontend changes

OpenAPI Generation Modes

The OpenAPI module automatically selects the optimal documentation generation approach:

  • AUTOMATIC Mode: Generate complete OpenAPI specs from Axis2 service metadata and annotations - ideal for new services
  • STATIC Mode: Use manually crafted OpenAPI schema files for precise API contracts - perfect for existing API specifications
  • HYBRID Mode: Combine automatic base generation with static schema enhancements - balances automation with customization for complex enterprise requirements

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 a complete financial services API demonstrating authentication, data management, and calculation services with full OpenAPI 3.0.1 documentation.

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 provides three comprehensive services demonstrating different aspects of enterprise REST API development:

  • AuthenticationService: Login/authentication with custom token generation
  • DataManagementService: Market data processing and financial calculation services
  • ExcelIntegrationService: Excel Add-in specific endpoints and metadata

Authentication Service

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

@Path("/api/auth")
@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 and return access token")
    public LoginResponse login(LoginRequest request) {
        // Token generation and validation logic
    }
}

Data Service

A data service with authenticated endpoints:

@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 and Swagger UI, configure the OpenAPI module in your axis2.xml:

<module ref="openapi" />

<!-- OpenAPI Module Configuration -->
<parameter name="openapi.generationMode">HYBRID</parameter>
<parameter name="openapi.staticSchemaPath">openapi-schema.json</parameter>
<parameter name="openapi.enableSwaggerUI">true</parameter>
<parameter name="openapi.swaggerUIPath">/swagger-ui</parameter>
<parameter name="openapi.enableCORS">true</parameter>

OpenAPI Configuration Parameters

  • generationMode: AUTOMATIC (introspection), STATIC (schema files), or HYBRID (combined)
  • staticSchemaPath: Path to static OpenAPI schema file (for STATIC/HYBRID modes)
  • enableSwaggerUI: Enable interactive Swagger UI (default: true)
  • swaggerUIPath: Swagger UI endpoint path (default: /swagger-ui)
  • enableCORS: Enable CORS headers for browser access (default: true)
  • apiTitle: API title in OpenAPI spec (default: "Apache Axis2 REST API")
  • apiVersion: API version (default: "1.0.0")

Static Schema Integration

For drop-in replacement scenarios, use STATIC or HYBRID mode with existing OpenAPI schemas:

<!-- STATIC mode: Use existing OpenAPI schema file -->
<parameter name="openapi.generationMode">STATIC</parameter>
<parameter name="openapi.staticSchemaPath">existing-api-schema.json</parameter>

<!-- HYBRID mode: Enhance introspection with static schema -->
<parameter name="openapi.generationMode">HYBRID</parameter>
<parameter name="openapi.staticSchemaPath">api-enhancements.json</parameter>

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":"password123"}' \
     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 custom bigdataToken header (maintaining frontend compatibility):

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:

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 (if supported)
http://localhost:8080/axis2/openapi.yaml

These endpoints are CORS-enabled 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: Set up OpenAPI module with STATIC mode using existing schemas
  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
  • Service Caching: OpenAPI spec generation results are cached for improved response times
  • CORS Optimization: Efficient CORS header handling for browser-based applications
  • 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 openapi.mar 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 enableSwaggerUI parameter is set to true
  2. Check the swaggerUIPath configuration
  3. Verify CORS settings if accessing from a different domain

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. Review OpenAPI spec generation caching configuration
  4. 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.