SQ.Api
1.0.4
dotnet add package SQ.Api --version 1.0.4
NuGet\Install-Package SQ.Api -Version 1.0.4
<PackageReference Include="SQ.Api" Version="1.0.4" />
<PackageVersion Include="SQ.Api" Version="1.0.4" />
<PackageReference Include="SQ.Api" />
paket add SQ.Api --version 1.0.4
#r "nuget: SQ.Api, 1.0.4"
#:package SQ.Api@1.0.4
#addin nuget:?package=SQ.Api&version=1.0.4
#tool nuget:?package=SQ.Api&version=1.0.4
SQ.Api
A comprehensive .NET library for interacting with SonarQube Server and SonarQube Cloud APIs. This library provides version-aware client functionality that automatically detects server capabilities and routes requests to the appropriate API endpoints.
Key Features
- 🔍 Automatic Version Detection: Detects SonarQube server version and capabilities
- 🔄 Multi-Version Support: Supports both V1 (legacy Web API) and V2 (modern REST API) endpoints
- ⚡ Auto-Selection: Automatically chooses the best available API version for each request
- ☁️ SonarQube Cloud Support: Full compatibility with SonarQube Cloud instances
- 🛡️ Robust Error Handling: Comprehensive error handling with detailed exception information
- 🔄 Retry Logic: Built-in retry policies with exponential backoff for transient failures
- 🔐 Authentication: Support for token-based authentication with secure token management
- 💉 Dependency Injection: Full support for .NET dependency injection patterns
- ⚡ Async/Await: Fully asynchronous API with cancellation token support
- 📊 Comprehensive API Coverage: Extensive endpoint coverage across all major SonarQube features
Architecture
Core Components
- SonarQubeClient: Main client interface providing access to all API functionality
- Version Detection: Automatic detection of server version and capabilities
- Endpoint Registry: Dynamic endpoint management based on server version
- Base Endpoints: Common functionality for V1 and V2 API implementations
- HTTP Client: Abstracted HTTP client with authentication and retry logic
Version Support
- V1 API: Legacy Web API endpoints (all SonarQube versions)
- V2 API: Modern REST API endpoints (SonarQube 10.0+ and SonarQube Cloud)
- Auto API: Automatically selects the best available API version
Supported Versions
| Version | Support Level | V1 API | V2 API | Edition Req | Notes |
|---|---|---|---|---|---|
| SonarQube 8.9 LTS | ✅ Full | ✅ | Community | EOL (End of Life) | |
| SonarQube 9.0-9.8 | ✅ Full | ✅ | Community | EOL | |
| SonarQube 9.9 LTS | ✅ Full | ✅ | Community | Supported until 2027 | |
| SonarQube 10.0-10.1 | ✅ Full | ✅ Basic | Community | Basic V2 endpoints | |
| SonarQube 10.2-10.3 | ✅ Full | ✅ Extended | Community | Extended V2 endpoints | |
| SonarQube 10.4+ | ✅ Full | ✅ Advanced | Community | Advanced V2 endpoints | |
| SonarQube 2025.1 LTA | ✅ Full | ✅ Advanced | Community | Long Term Active | |
| SonarQube 2025.4 | ✅ Full | ✅ Advanced | Community | Latest features | |
| SonarQube 2026.1 LTA | ✅ Full | ✅ Advanced | Community | Current release | |
| SonarQube Cloud | ✅ Full | ✅ All | Cloud | Always latest |
V2 Endpoint Version Requirements
| Endpoint Group | Minimum Version | Edition Required | Available In |
|---|---|---|---|
| V2 System | 10.0+ | Community | All 10.x+ and 202x+ |
| V2 Users | 10.0+ | Community | All 10.x+ and 202x+ |
| V2 Groups | 10.0+ | Community | All 10.x+ and 202x+ |
| V2 Issues | 10.2+ | Enterprise | 10.2+ Enterprise, SonarQube Cloud |
Edition Feature Matrix
| Feature | Community | Developer | Enterprise | Data Center | SonarQube Cloud |
|---|---|---|---|---|---|
| V1 API Endpoints | ✅ | ✅ | ✅ | ✅ | ✅ |
| V2 System/Users/Groups | ✅ | ✅ | ✅ | ✅ | ✅ |
| V2 Issues | ❌ | ❌ | ✅ | ✅ | ✅ |
Installation
NuGet Package Manager
Install-Package SQ.Api
.NET CLI
dotnet add package SQ.Api
Package Reference
<PackageReference Include="SQ.Api" Version="1.0.0" />
Quick Start
Basic Usage with Dependency Injection
using Microsoft.Extensions.DependencyInjection;
using SonarQube.API.Extensions;
var services = new ServiceCollection();
// Add required services
services.AddLogging();
services.AddHttpClient();
// Add SonarQube API
services.AddSonarQubeApi("https://sonarcloud.io", "your-token-here");
var serviceProvider = services.BuildServiceProvider();
var client = serviceProvider.GetRequiredService<ISonarQubeClient>();
// Test connection
var isConnected = await client.TestConnectionAsync();
Console.WriteLine($"Connected: {isConnected}");
// Detect version
var versionResult = await client.DetectVersionAsync();
if (versionResult.IsSuccess)
{
Console.WriteLine($"Version: {versionResult.Data.Version}");
Console.WriteLine($"Supports V2 API: {versionResult.Data.Version.SupportsV2Api()}");
}
Using Client Factory
services.AddSonarQubeApiFactory();
var factory = serviceProvider.GetRequiredService<ISonarQubeClientFactory>();
var options = new SonarQubeClientOptions
{
BaseUrl = "https://sonar.example.com",
Authentication = new AuthenticationOptions { Token = "your-token" }
};
using var client = factory.CreateClient(options);
Manual Configuration
services.AddSonarQubeApi(options =>
{
options.BaseUrl = "https://sonar.example.com";
options.Authentication.Token = "your-token";
options.TimeoutSeconds = 30;
options.MaxRetryAttempts = 3;
options.VerboseLogging = true;
});
API Usage
Version Detection
// Automatic version detection
var versionResult = await client.DetectVersionAsync();
if (versionResult.IsSuccess)
{
var version = versionResult.Data;
Console.WriteLine($"Server: {version.ServerUrl}");
Console.WriteLine($"Version: {version.Version.ToVersionString()}");
Console.WriteLine($"Raw Version: {version.RawVersion}");
Console.WriteLine($"Is SonarCloud: {version.IsSonarCloud}");
}
Endpoint Access
// Use auto-selected endpoints (recommended)
var statusResult = await client.Auto.System.GetStatusAsync();
// Use specific API versions
if (client.V2 != null)
{
var v2StatusResult = await client.V2.System.GetStatusAsync();
}
if (client.V1 != null)
{
var v1StatusResult = await client.V1.System.GetStatusAsync();
}
Error Handling
try
{
var result = await client.Auto.System.GetStatusAsync();
if (result.IsSuccess)
{
// Handle success
var status = result.Data;
}
else
{
// Handle API error
Console.WriteLine($"API Error: {result.ErrorMessage}");
}
}
catch (SonarQubeApiException ex)
{
// Handle HTTP/network errors
Console.WriteLine($"HTTP Error: {ex.Message}");
Console.WriteLine($"Status Code: {ex.StatusCode}");
}
Version and Edition Validation
The library automatically validates version and edition requirements before making API calls:
using SonarQube.API.Common.Exceptions;
using SonarQube.API.Common.Version;
try
{
// This endpoint requires 10.2+ Enterprise edition
var result = await client.V2.Issues.GetFixSuggestionsAsync(request);
Console.WriteLine($"Fix suggestions: {result.Data}");
}
catch (VersionNotSupportedException ex)
{
Console.WriteLine($"Version Error: {ex.Message}");
Console.WriteLine($"Current: {ex.CurrentVersion.ToVersionString()}");
Console.WriteLine($"Required: {ex.RequiredVersion.ToVersionString()}");
Console.WriteLine("Upgrade your SonarQube instance to use this feature.");
}
catch (EditionNotSupportedException ex)
{
Console.WriteLine($"Edition Error: {ex.Message}");
Console.WriteLine($"Current: {ex.CurrentEdition.ToEditionString()}");
Console.WriteLine($"Required: {ex.RequiredEdition.ToEditionString()}");
Console.WriteLine("Upgrade to Enterprise Edition to use this feature.");
}
Checking Server Capabilities:
// Detect server version and capabilities
var versionResult = await client.DetectVersionAsync();
if (versionResult.IsSuccess)
{
var info = versionResult.Data;
Console.WriteLine($"Version: {info.Version.ToVersionString()}");
Console.WriteLine($"Edition: {info.Edition.ToEditionString()}");
Console.WriteLine($"Supports V1 API: {info.SupportsV1Api()}");
Console.WriteLine($"Supports V2 API: {info.SupportsV2Api()}");
}
Available Endpoints
V1 API Endpoints (Available in all SonarQube versions)
System Endpoints
- System Status: Get system status information
- System Health: Get system health information
- System Info: Get detailed system information
- Ping: Test server connectivity
Projects Endpoints
- Search Projects: Search for projects with filtering
- Get Project: Get detailed project information
- Create Project: Create new projects
- Delete Project: Delete existing projects
- Update Project Key: Change project identifier
- Update Visibility: Change project visibility (public/private)
- Bulk Delete: Delete multiple projects
Issues Endpoints
- Search Issues: Search and filter issues
- Get Issue: Get detailed issue information
- Assign Issue: Assign issues to users
- Add Comment: Add comments to issues
- Set Severity: Change issue severity
- Set Type: Change issue type
- Transition Issue: Change issue status
- Bulk Change: Apply changes to multiple issues
Quality Gates Endpoints
- List Quality Gates: Get all quality gates
- Show Quality Gate: Get quality gate details
- Create Quality Gate: Create new quality gates
- Delete Condition: Remove quality gate conditions
- Update Condition: Modify quality gate conditions
- Project Status: Get quality gate status for projects
- Select/Deselect: Associate quality gates with projects
Metrics Endpoints
- Search Metrics: Find available metrics
- Component Measures: Get metrics for components
- Measure History: Get historical metric data
Users Endpoints
- Search Users: Find users with filtering
- Get Current User: Get current user information
- Create User: Create new users
- Update User: Modify user information
- Delete User: Remove users
- User Groups: Get user group memberships
Analysis Endpoints
- Search Analysis: Find project analyses
- Analysis History: Get analysis history
- Create Event: Create analysis events
- Update Event: Modify analysis events
- Delete Event: Remove analysis events
V2 API Endpoints (Available in SonarQube 10.0+ and SonarQube Cloud)
System Endpoints
- System Status: Enhanced system status with additional metrics
- System Health: Improved health monitoring
Issues Endpoints
- Fix Suggestions: Get suggested fixes for issues
Groups Endpoints
- Group Memberships: Manage group memberships
- Groups Management: Advanced group management
Users Endpoints
- Enhanced User Search: Improved user search capabilities
- User Management: Advanced user management features
Auto Endpoints
- Auto System: Automatically selects best available system endpoints
- More auto endpoints will be added as the library expands
Configuration Options
SonarQubeClientOptions
public class SonarQubeClientOptions
{
/// <summary>The base URL of the SonarQube instance (required)</summary>
public string BaseUrl { get; set; }
/// <summary>Authentication settings (required)</summary>
public AuthenticationOptions Authentication { get; set; }
/// <summary>HTTP timeout in seconds (default: 30)</summary>
public int TimeoutSeconds { get; set; } = 30;
/// <summary>Maximum retry attempts for failed requests (default: 3)</summary>
public int MaxRetryAttempts { get; set; } = 3;
/// <summary>User agent string for HTTP requests</summary>
public string UserAgent { get; set; } = "SonarQube.API";
/// <summary>Enable verbose request/response logging</summary>
public bool VerboseLogging { get; set; } = false;
/// <summary>Validate SSL certificates (default: true)</summary>
public bool ValidateSslCertificate { get; set; } = true;
/// <summary>Retry policy settings</summary>
public RetryPolicySettings RetryPolicy { get; set; } = new();
}
AuthenticationOptions
public class AuthenticationOptions
{
/// <summary>Authentication token for SonarQube Server/SonarQube Cloud</summary>
public string Token { get; set; }
/// <summary>Username for basic authentication (legacy)</summary>
public string? Username { get; set; }
/// <summary>Password for basic authentication (legacy)</summary>
public string? Password { get; set; }
}
RetryPolicySettings
public class RetryPolicySettings
{
/// <summary>Maximum number of retry attempts (default: 3)</summary>
public int MaxRetryAttempts { get; set; } = 3;
/// <summary>Base delay between retries in milliseconds (default: 1000)</summary>
public int BaseDelayMilliseconds { get; set; } = 1000;
/// <summary>Maximum delay between retries in milliseconds (default: 30000)</summary>
public int MaxDelayMilliseconds { get; set; } = 30000;
/// <summary>Exponential backoff multiplier (default: 2.0)</summary>
public double BackoffMultiplier { get; set; } = 2.0;
}
Advanced Usage
Custom HTTP Client Configuration
services.AddHttpClient<ISonarQubeClient>(client =>
{
client.Timeout = TimeSpan.FromSeconds(60);
client.DefaultRequestHeaders.Add("Custom-Header", "Value");
});
services.AddSonarQubeApi(options =>
{
options.BaseUrl = "https://sonar.example.com";
options.Authentication.Token = "your-token";
});
Version-Specific API Usage
// Check server version and capabilities
var versionResult = await client.DetectVersionAsync();
if (versionResult.IsSuccess)
{
var version = versionResult.Data;
if (version.Version.SupportsV2Api())
{
// Use V2 endpoints for enhanced features
var fixSuggestions = await client.V2.Issues.GetFixSuggestionsAsync(request);
}
else
{
// Fall back to V1 endpoints
var issues = await client.V1.Issues.SearchAsync(request);
}
}
Pagination Support
// Manual pagination
var request = new ProjectSearchRequest
{
PageIndex = 1,
PageSize = 100
};
var result = await client.V1.Projects.SearchAsync(request);
if (result.IsSuccess)
{
var projects = result.Data.Components;
var paging = result.Data.Paging;
Console.WriteLine($"Page {paging.PageIndex} of {paging.Total / paging.PageSize + 1}");
}
Cancellation Token Support
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
try
{
var result = await client.V1.Projects.SearchAsync(request, cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cancelled");
}
Testing
Running Tests
# Run all tests
dotnet test tests/SQ.Api.Tests/
# Run specific test category
dotnet test tests/SQ.Api.Tests/ --filter Category=Integration
# Run with verbose output
dotnet test tests/SQ.Api.Tests/ --logger "console;verbosity=detailed"
Test Infrastructure
The library includes comprehensive integration tests that run against multiple SonarQube versions:
- Docker-based Testing: Tests run against real SonarQube instances
- Version Matrix: Tests validate compatibility across SonarQube 9.9, 10.x, 2025.1, 2025.4, 2026.1, and SonarQube Cloud
- Automated Setup: Test infrastructure automatically starts and manages SonarQube containers
# Run API integration tests against all SonarQube versions
./scripts/run-api-tests-with-coverage.sh
# Run against a specific version
./scripts/run-api-tests-with-coverage.sh --version 2026-1
# Run all tests (unit + API + CLI integration + scenario)
./scripts/run-all-tests-with-coverage.sh
Contributing
We welcome contributions! This library follows these established patterns:
- Async/Await Pattern: All API calls are async with cancellation token support
- Error Handling: Comprehensive error handling with typed exceptions
- Testing: Full test coverage with MSTest and version-matrix testing
- Logging: Structured logging for diagnostics and debugging
- Versioning: Follows semantic versioning principles
Development Setup
# Clone the repository
git clone https://github.com/jonlipsky/sonarqube-cli.git
cd sonarqube-cli
# Build the solution
dotnet build
# Run unit tests
dotnet test tests/SQ.Cli.Tests
# Run integration tests (requires Docker and SonarQube license)
./scripts/run-api-tests-with-coverage.sh
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- Issues: Report bugs and feature requests on GitHub Issues
- Discussions: Join the conversation on GitHub Discussions
Related Projects
- SonarQube CLI: Full-featured CLI application built on this library
- SonarQube: The SonarQube platform itself
- SonarQube Cloud: Hosted SonarQube service
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.Http (>= 10.0.2)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.2)
- Polly (>= 8.6.5)
- Polly.Extensions.Http (>= 3.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Initial release of the SQ.Api library. Includes API coverage for both V1 and V2 endpoints, automatic version detection, robust error handling, and support for SonarQube Server and SonarQube Cloud.