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:
Configuration Parameters:
| Parameter | Type | Description | Default |
|---|---|---|---|
EnableScalar |
bool |
Enable or disable Scalar UI | false |
Environment-Specific Configuration¶
Development:
Production:
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:
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¶
Custom HTTP Client¶
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:
Consistency: Both tools show the same API documentation from the same source.
Best Practices¶
Do's¶
-
Enable Scalar in Development
-
Use Descriptive API Titles
-
Configure Rate Limiting Exemption
-
Document APIs with XML Comments
-
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¶
-
Don't Expose Scalar in Production Without Authentication
-
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 } -
Don't Use Hardcoded Values in Examples
Security Considerations¶
Production Deployment¶
Best Practices:
-
Disable in Production (if not needed):
-
Use Authentication Middleware:
-
Restrict Access by IP:
-
Use Authorization Policies:
Rate Limiting¶
Scalar endpoints should be exempt from rate limiting:
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:
- Verify Feature Flags:
- Ensure
Scalarfeature flag is enabled -
Ensure at least one of
UseGrpc,UseRestApi, orUseAzureFunctionis enabled -
Check Endpoint Registration:
-
Verify OpenAPI Endpoint:
- Ensure
/swagger/v1/swagger.jsonis accessible - Scalar reads from this endpoint
Issue: OpenAPI Specification Not Found¶
Symptoms: Scalar shows "OpenAPI specification not found" error.
Solutions: 1. Verify Swagger Configuration:
-
Check Route Pattern:
-
Test OpenAPI Endpoint:
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
Related Documentation¶
- REST API: REST API implementation and OpenAPI specification
- Swagger: Swagger UI configuration and usage
- API Versioning: API versioning strategies and OpenAPI support
- Documentation as Code: Documentation practices including API documentation
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.