Skip to content

Scalar API Documentation in ConnectSoft Microservice Template

Purpose & Overview

Scalar is an open-source, offline-first platform for building interactive API documentation and clients from OpenAPI specifications. In the ConnectSoft Microservice Template, Scalar serves as a modern alternative to Swagger UI, providing a beautiful, performant, and feature-rich interface for exploring and testing REST APIs, gRPC services, and Azure Functions.

Scalar provides:

  • Modern UI: Beautiful, responsive interface with dark theme support
  • Interactive Testing: Try-it-out functionality for API endpoints
  • Offline-First: Works without internet connection after initial load
  • Code Generation: Built-in client code samples in multiple languages
  • Performance: Fast rendering of large APIs with optimized loading
  • Mobile Support: Responsive design for mobile devices
  • OpenAPI Integration: Native support for OpenAPI 3.0 specifications
  • Customization: Extensive theming and configuration options

Scalar Philosophy

Scalar provides a modern, developer-friendly alternative to Swagger UI for API documentation. It offers better performance, improved user experience, and additional features like code generation while maintaining full compatibility with OpenAPI specifications. Scalar can be used alongside Swagger UI, allowing teams to choose the best tool for their needs or provide both options to API consumers.

Architecture Overview

Scalar Integration

OpenAPI Specification (Swagger)
    ├── /swagger/v1/swagger.json (OpenAPI 3.0)
    └── /swagger/{documentName}/swagger.json
Scalar.AspNetCore
    ├── MapScalarApiReference()
    ├── Configuration Options
    └── Route Pattern Configuration
Scalar UI Endpoint
    └── /scalar (default route)
Interactive API Documentation
    ├── Endpoint Explorer
    ├── Try-It-Out
    ├── Code Generation
    └── Schema Viewer

Scalar vs Swagger UI

Feature Scalar Swagger UI
Performance Fast rendering, optimized for large APIs Can be slow with large APIs
UI/UX Modern, beautiful interface Traditional interface
Mobile Support Responsive design Limited mobile support
Code Generation Built-in multi-language code samples Requires external tools
Offline Support Works offline after initial load Requires internet
Theming Extensive customization options Limited customization
Bundle Size Smaller bundle size Larger bundle size

Service Registration

MapScalar Extension

Scalar is mapped via MapScalar() extension method:

// ScalarExtensions.cs
internal static IEndpointRouteBuilder MapScalar(this IEndpointRouteBuilder endpoints)
{
    ArgumentNullException.ThrowIfNull(endpoints);

    ScalarOptions scalarOptions = endpoints.ServiceProvider
        .GetRequiredService<IOptions<ScalarOptions>>().Value;

    if (scalarOptions.EnableScalar)
    {
        var endpointsBuilder = endpoints.MapScalarApiReference(configureOptions =>
        {
            configureOptions
                .WithTitle("ConnectSoft.MicroserviceTemplate's microservice back-end API")
                .WithOpenApiRoutePattern("/swagger/{documentName}/swagger.json");
        });

#if RateLimiting
        endpointsBuilder.DisableRateLimiting();
#endif
    }

    return endpoints;
}

Registration in MicroserviceRegistrationExtensions

Scalar is conditionally registered based on feature flags:

// MicroserviceRegistrationExtensions.cs
#if Scalar && (UseGrpc || UseRestApi || UseAzureFunction)
    endpoints.MapScalar();
#endif

Conditions: - Scalar feature flag must be enabled - At least one of: UseGrpc, UseRestApi, or UseAzureFunction must be enabled

Configuration

ScalarOptions

Configuration Class:

// ScalarOptions.cs
public sealed class ScalarOptions
{
    public const string ScalarOptionsSectionName = "Scalar";

    [Required]
    required public bool EnableScalar { get; set; }
}

appsettings.json Configuration

Example Configuration:

{
  "Scalar": {
    "EnableScalar": true
  }
}

Configuration Parameters:

Parameter Type Description Default
EnableScalar bool Enable or disable Scalar UI false

Environment-Specific Configuration

Development:

{
  "Scalar": {
    "EnableScalar": true
  }
}

Production:

{
  "Scalar": {
    "EnableScalar": false
  }
}

Note: Scalar can be enabled in production for internal API documentation, but consider security implications and access controls.

Scalar UI Features

1. Interactive API Explorer

Features: - Browse all API endpoints organized by tags - View request/response schemas - Expand/collapse endpoint details - Search functionality for endpoints

Usage: 1. Navigate to /scalar endpoint 2. Browse endpoints by tag or search 3. Click on endpoint to view details

2. Try-It-Out Functionality

Features: - Execute API requests directly from the UI - View request/response in real-time - Configure request parameters - Set authentication headers - View response status codes and body

Example:

// API endpoint
[HttpPost("api/FeatureA/FeatureAUseCaseA")]
public async Task<ActionResult> CreateFeatureA(CreateFeatureARequest request)
{
    // Implementation
}

// In Scalar UI:
// 1. Click "Try it out" button
// 2. Fill in request body
// 3. Click "Execute"
// 4. View response

3. Code Generation

Supported Languages: - JavaScript (Fetch, Axios) - TypeScript - cURL - Python (requests) - C# (HttpClient) - PHP - Go - Ruby - Java - Kotlin - Swift - And more

Usage: 1. Select endpoint in Scalar UI 2. Click "Code" tab 3. Select language 4. Copy generated code

Example Generated Code:

// C# HttpClient
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.example.com/api/FeatureA/FeatureAUseCaseA");
request.Headers.Add("Authorization", "Bearer YOUR_TOKEN");
var content = new StringContent("{\"name\":\"Example\"}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());

4. Schema Viewer

Features: - View request/response schemas - Expand nested objects - See data types and constraints - View required vs optional fields - Example values

Benefits: - Understand API structure quickly - Validate request structure before sending - See all possible response fields

5. Authentication Support

Supported Authentication Types: - Bearer Token (JWT) - API Key - Basic Auth - OAuth 2.0 - Custom headers

Configuration:

// ScalarExtensions.cs
endpoints.MapScalarApiReference(configureOptions =>
{
    configureOptions
        .WithTitle("API Documentation")
        .WithOpenApiRoutePattern("/swagger/{documentName}/swagger.json")
        .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
});

6. Dark Theme

Features: - Beautiful dark theme by default - Light theme option - Customizable colors - Better readability

OpenAPI Integration

Route Pattern Configuration

Scalar reads OpenAPI specifications from Swagger endpoints:

configureOptions
    .WithOpenApiRoutePattern("/swagger/{documentName}/swagger.json");

Supported Patterns: - /swagger/{documentName}/swagger.json - Standard Swagger pattern - /openapi/{documentName}.json - OpenAPI pattern - Custom routes via configuration

Multiple API Versions

Scalar supports multiple API versions:

configureOptions
    .WithOpenApiRoutePattern("/swagger/{documentName}/swagger.json")
    .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);

Usage: - Navigate to /scalar endpoint - Select API version from dropdown - View documentation for selected version

Advanced Configuration

Custom Title and Configuration

endpoints.MapScalarApiReference(configureOptions =>
{
    configureOptions
        .WithTitle("ConnectSoft.MicroserviceTemplate's microservice back-end API")
        .WithOpenApiRoutePattern("/swagger/{documentName}/swagger.json")
        .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient)
        .WithTheme(ScalarTheme.Default);
});

Custom Theme

configureOptions
    .WithTheme(new ScalarTheme
    {
        // Custom theme configuration
    });

Custom HTTP Client

configureOptions
    .WithDefaultHttpClient(ScalarTarget.JavaScript, ScalarClient.Fetch);

Integration with Swagger

Coexistence

Scalar and Swagger UI can coexist:

// Both enabled
#if Swagger && (UseGrpc || UseRestApi || UseAzureFunction)
    endpoints.MapMicroserviceSwagger();
#endif
#if Scalar && (UseGrpc || UseRestApi || UseAzureFunction)
    endpoints.MapScalar();
#endif

Benefits: - Provide choice to API consumers - Different teams can prefer different tools - Gradual migration from Swagger UI

Shared OpenAPI Specification

Both Scalar and Swagger UI use the same OpenAPI specification:

/swagger/v1/swagger.json
    ├── Swagger UI (/swagger)
    └── Scalar (/scalar)

Consistency: Both tools show the same API documentation from the same source.

Best Practices

Do's

  1. Enable Scalar in Development

    {
      "Scalar": {
        "EnableScalar": true
      }
    }
    

  2. Use Descriptive API Titles

    configureOptions
        .WithTitle("ConnectSoft.MicroserviceTemplate's microservice back-end API");
    

  3. Configure Rate Limiting Exemption

    var endpointsBuilder = endpoints.MapScalarApiReference(...);
    endpointsBuilder.DisableRateLimiting(); // Allow unthrottled access to docs
    

  4. Document APIs with XML Comments

    /// <summary>
    /// Creates a new microservice aggregate root.
    /// </summary>
    /// <param name="request">The creation request.</param>
    /// <returns>The created aggregate root.</returns>
    [HttpPost]
    public async Task<ActionResult> Create(CreateRequest request)
    {
        // Implementation
    }
    

  5. Use OpenAPI Annotations

    [SwaggerOperation(
        Summary = "Creates a new aggregate root",
        Description = "This endpoint creates a new aggregate root with the provided data.",
        OperationId = "CreateAggregateRoot",
        Tags = ["AggregateRoots"])]
    [SwaggerResponse(StatusCodes.Status200OK, "Created successfully")]
    [SwaggerResponse(StatusCodes.Status400BadRequest, "Invalid request")]
    public async Task<ActionResult> Create(CreateRequest request)
    {
        // Implementation
    }
    

Don'ts

  1. Don't Expose Scalar in Production Without Authentication

    // ❌ BAD - Scalar accessible without auth
    {
      "Scalar": {
        "EnableScalar": true
      }
    }
    
    // ✅ GOOD - Disable in production or require authentication
    {
      "Scalar": {
        "EnableScalar": false  // Or use authentication middleware
      }
    }
    

  2. Don't Skip XML Documentation

    // ❌ BAD - No documentation
    [HttpPost]
    public async Task<ActionResult> Create(CreateRequest request)
    {
        // Implementation
    }
    
    // ✅ GOOD - Documented
    /// <summary>
    /// Creates a new aggregate root.
    /// </summary>
    [HttpPost]
    public async Task<ActionResult> Create(CreateRequest request)
    {
        // Implementation
    }
    

  3. Don't Use Hardcoded Values in Examples

    // ❌ BAD - Hardcoded example
    [SwaggerRequestExample(typeof(CreateRequest), typeof(CreateRequestExample))]
    
    // ✅ GOOD - Use realistic examples
    [SwaggerRequestExample(typeof(CreateRequest), typeof(RealisticCreateRequestExample))]
    

Security Considerations

Production Deployment

Best Practices:

  1. Disable in Production (if not needed):

    {
      "Scalar": {
        "EnableScalar": false
      }
    }
    

  2. Use Authentication Middleware:

    // Require authentication for Scalar endpoint
    app.MapScalarApiReference(...)
        .RequireAuthorization();
    

  3. Restrict Access by IP:

    // Restrict to internal IPs
    app.MapScalarApiReference(...)
        .RequireHost("internal.example.com");
    

  4. Use Authorization Policies:

    app.MapScalarApiReference(...)
        .RequireAuthorization("ApiDocumentationPolicy");
    

Rate Limiting

Scalar endpoints should be exempt from rate limiting:

#if RateLimiting
    endpointsBuilder.DisableRateLimiting();
#endif

Reason: Documentation endpoints are typically low-traffic and should not be throttled.

Troubleshooting

Issue: Scalar UI Not Loading

Symptoms: Scalar endpoint returns 404 or blank page.

Solutions: 1. Check Configuration:

{
  "Scalar": {
    "EnableScalar": true
  }
}

  1. Verify Feature Flags:
  2. Ensure Scalar feature flag is enabled
  3. Ensure at least one of UseGrpc, UseRestApi, or UseAzureFunction is enabled

  4. Check Endpoint Registration:

    #if Scalar && (UseGrpc || UseRestApi || UseAzureFunction)
        endpoints.MapScalar();
    #endif
    

  5. Verify OpenAPI Endpoint:

  6. Ensure /swagger/v1/swagger.json is accessible
  7. Scalar reads from this endpoint

Issue: OpenAPI Specification Not Found

Symptoms: Scalar shows "OpenAPI specification not found" error.

Solutions: 1. Verify Swagger Configuration:

{
  "Swagger": {
    "EnableSwagger": true
  }
}

  1. Check Route Pattern:

    configureOptions
        .WithOpenApiRoutePattern("/swagger/{documentName}/swagger.json");
    

  2. Test OpenAPI Endpoint:

    curl http://localhost:5000/swagger/v1/swagger.json
    

Issue: Code Generation Not Working

Symptoms: Code samples not appearing or incorrect.

Solutions: 1. Check OpenAPI Specification: Ensure endpoints are properly documented 2. Verify Request/Response Schemas: Ensure schemas are defined in OpenAPI 3. Check Scalar Version: Update to latest version if issues persist

Summary

Scalar API documentation in the ConnectSoft Microservice Template provides:

  • Modern UI: Beautiful, responsive interface with dark theme
  • Interactive Testing: Try-it-out functionality for API endpoints
  • Code Generation: Built-in client code samples in multiple languages
  • Performance: Fast rendering optimized for large APIs
  • Offline Support: Works without internet after initial load
  • OpenAPI Integration: Native support for OpenAPI 3.0 specifications
  • Mobile Support: Responsive design for mobile devices
  • Security: Configurable authentication and access controls

By following these patterns, teams can:

  • Provide Better Developer Experience: Modern, intuitive API documentation interface
  • Enable Interactive Testing: Developers can test APIs directly from documentation
  • Generate Client Code: Automatically generate code samples for API consumers
  • Improve API Discovery: Better organization and search capabilities
  • Support Multiple Platforms: Mobile-friendly responsive design

Scalar provides a modern, developer-friendly alternative to Swagger UI, offering better performance, improved user experience, and additional features while maintaining full compatibility with OpenAPI specifications.