Python SonarQube API Wrapper
python-sonarqube-api is a Python wrapper for the SonarQube and SonarCloud API, providing a convenient interface to interact with SonarQube Community, Enterprise, and SonarCloud instances. It supports Python 2.7 and 3.3+ (though modern usage typically implies Python 3.6+). The library is actively maintained, with version 2.0.5 currently available, facilitating integration of SonarQube's static analysis capabilities into Python applications and CI/CD pipelines.
Common errors
-
ModuleNotFoundError: No module named 'sonarqube_api'
cause Attempting to import from an old or different package name. The current official package is `python-sonarqube-api` and its top-level module is `sonarqube`.fixChange your import statement from `from sonarqube_api import ...` to `from sonarqube import ...` (e.g., `from sonarqube import SonarQubeClient`). -
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: http://localhost:9000/api/...
cause Invalid SonarQube/SonarCloud authentication token or incorrect username/password. This often means the credentials provided are wrong or lack the necessary permissions for the API endpoint being accessed.fixDouble-check your `SONARQUBE_TOKEN` or `user`/`password` values. Ensure the user associated with the token has the required permissions in SonarQube/SonarCloud. Also, verify the `sonarqube_url` is correct and reachable. -
KeyError: 'edition' or 'Statistics'
cause Attempting to access the 'edition' or 'Statistics' key from the `/api/system/info` response on SonarQube versions 9.7.1 or later, where these fields were removed or changed.fixFor edition information on licensed SonarQube instances (Developer, Enterprise, Data Center), use the `/api/editions/show_license` endpoint. Community Edition no longer exposes this field via `/api/system/info`. Consult the SonarQube Web API documentation for your specific SonarQube version to confirm available endpoints and response structures.
Warnings
- breaking SonarQube API changes in versions 9.7.1 and later removed the 'Statistics.edition' field from the `/api/system/info` endpoint.
- gotcha SonarQube API methods that return large datasets are often paginated by the server. The `python-sonarqube-api` client methods frequently return generators to handle this efficiently.
- gotcha Token-based authentication is the recommended and more secure method for programmatic access to SonarQube/SonarCloud APIs over username/password.
- gotcha Different client classes exist for different SonarQube environments: `SonarQubeClient` for SonarQube Community/Enterprise, `SonarCloudClient` for SonarCloud, and `SonarEnterpriseClient` specifically for SonarQube Enterprise Edition.
Install
-
pip install --upgrade python-sonarqube-api
Imports
- SonarQubeClient
from sonarqube import SonarQubeClient
- SonarCloudClient
from sonarqube import SonarCloudClient
- SonarEnterpriseClient
from sonarqube import SonarEnterpriseClient
- SonarAPIHandler
from sonarqube_api import SonarAPIHandler
from sonarqube import SonarQubeClient
Quickstart
import os
from sonarqube import SonarQubeClient
# Configure connection details using environment variables for security
SONARQUBE_URL = os.environ.get('SONARQUBE_URL', 'http://localhost:9000')
SONARQUBE_TOKEN = os.environ.get('SONARQUBE_TOKEN', 'YOUR_SONARQUBE_TOKEN') # Or use user/password
# Initialize the SonarQube client
try:
client = SonarQubeClient(sonarqube_url=SONARQUBE_URL, token=SONARQUBE_TOKEN)
# Example: Fetch all projects
print(f"Connected to SonarQube at {SONARQUBE_URL}")
print("Fetching projects...")
projects = list(client.projects.search_projects())
if projects:
print(f"Found {len(projects)} projects:")
for project in projects[:3]: # Print first 3 projects
print(f" - {project.get('name')} (Key: {project.get('key')})")
else:
print("No projects found or accessible.")
except Exception as e:
print(f"An error occurred: {e}")
print("Please ensure SonarQube is running and accessible, and your token/credentials are correct.")
print("For SonarCloud, use SonarCloudClient and 'sonarcloud_url' parameter.")