### SonarQube SDK Issue Management Examples (Python) Source: https://sonarqube-sdk.readthedocs.io/en/latest/_sources/quickstart.rst Shows how to search for issues within a SonarQube project, filtering by severity, and how to transition the status of a specific issue. ```python # Get all critical issues issues = client.issues.search( project_keys=["my-project"], severities=["CRITICAL", "BLOCKER"] ) for issue in issues.issues: print(f"Issue: {issue.message}") ``` ```python # Mark issue as resolved client.issues.do_transition( issue="AXoN-12345", transition="resolve" ) ``` -------------------------------- ### SonarQube SDK Project Management Examples (Python) Source: https://sonarqube-sdk.readthedocs.io/en/latest/_sources/quickstart.rst Illustrates how to search for existing SonarQube projects, optionally with filters, and how to create a new project with specified name, key, and visibility. ```python # Search all projects projects = client.projects.search() # Search with filter projects = client.projects.search(q="backend") # Iterate over results for project in projects.components: print(f"Project: {project.name} ({project.key})") ``` ```python project = client.projects.create( name="My Project", project="my-project", visibility="private" ) ``` -------------------------------- ### SonarQube SDK Authentication Examples (Python) Source: https://sonarqube-sdk.readthedocs.io/en/latest/_sources/quickstart.rst Demonstrates how to authenticate with the SonarQube API using either token-based authentication (recommended) or basic authentication with username and password. ```python from sonarqube import SonarQubeClient client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token" ) ``` ```python from sonarqube import SonarQubeClient client = SonarQubeClient( base_url="https://sonarqube.example.com", username="admin", password="admin" ) ``` -------------------------------- ### Install Sonarqube SDK from Source Source: https://sonarqube-sdk.readthedocs.io/en/latest/installation Installs the Sonarqube SDK by cloning the repository and installing from local source. Requires Git and pip. ```bash git clone https://github.com/silasvasconcelos/sonarqube-sdk.git cd sonarqube-sdk pip install -e . ``` -------------------------------- ### Quick Start: SonarQube SDK Python Example Source: https://sonarqube-sdk.readthedocs.io/en/latest/_sources/index.rst Demonstrates how to initialize the SonarQube SDK client using token authentication and perform basic operations like searching for projects and retrieving issues. Requires the `sonarqube-sdk` package. ```python from sonarqube import SonarQubeClient # Initialize client with token authentication client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token" ) # Search for projects projects = client.projects.search(q="backend") for project in projects.components: print(f"Project: {project.name}") # Get issues issues = client.issues.search( project_keys=["my-project"], severities=["CRITICAL", "BLOCKER"] ) ``` -------------------------------- ### Development Installation of Sonarqube SDK Source: https://sonarqube-sdk.readthedocs.io/en/latest/installation Installs the Sonarqube SDK with development dependencies using a Makefile. This is suitable for contributors and developers. ```bash git clone https://github.com/silasvasconcelos/sonarqube-sdk.git cd sonarqube-sdk make dev ``` -------------------------------- ### Transition an Issue with SonarQube SDK Source: https://sonarqube-sdk.readthedocs.io/en/latest/quickstart Shows how to perform a transition on a specific issue in SonarQube using the SDK. This example demonstrates marking an issue as 'resolved' by providing the issue key and the desired transition type. ```python # Mark issue as resolved client.issues.do_transition( issue="AXoN-12345", transition="resolve" ) ``` -------------------------------- ### Create a Project with SonarQube SDK Source: https://sonarqube-sdk.readthedocs.io/en/latest/quickstart Demonstrates the process of creating a new project in SonarQube using the SDK. This includes specifying the project's name, a unique project key, and its visibility setting (e.g., private). ```python project = client.projects.create( name="My Project", project="my-project", visibility="private" ) ``` -------------------------------- ### SonarQube SDK Error Handling Examples (Python) Source: https://sonarqube-sdk.readthedocs.io/en/latest/_sources/quickstart.rst Demonstrates how to implement error handling for common SonarQube API exceptions such as authentication errors, not found errors, and permission errors. ```python from sonarqube import SonarQubeClient from sonarqube.exceptions import ( SonarQubeAuthenticationError, SonarQubeNotFoundError, SonarQubePermissionError, ) client = SonarQubeClient(base_url="...", token="...") try: project = client.projects.search(q="test") except SonarQubeAuthenticationError: print("Invalid credentials") except SonarQubeNotFoundError: print("Resource not found") except SonarQubePermissionError: print("Permission denied") ``` -------------------------------- ### Search Issues with SonarQube SDK Source: https://sonarqube-sdk.readthedocs.io/en/latest/quickstart Provides an example of searching for issues within SonarQube using the SDK. It demonstrates how to filter issues by project keys and severity levels, and how to iterate through the found issues to print their messages. ```python # Get all critical issues issues = client.issues.search( project_keys=["my-project"], severities=["CRITICAL", "BLOCKER"] ) for issue in issues.issues: print(f"Issue: {issue.message}") ``` -------------------------------- ### Search and Iterate Projects with SonarQube SDK Source: https://sonarqube-sdk.readthedocs.io/en/latest/quickstart Shows how to search for projects within SonarQube using the SDK. It covers searching all projects, applying filters, and iterating through the returned project components to display their names and keys. ```python # Search all projects projects = client.projects.search() # Search with filter projects = client.projects.search(q="backend") # Iterate over results for project in projects.components: print(f"Project: {project.name} ({project.key})") ``` -------------------------------- ### Authenticate with SonarQube SDK (Token) Source: https://sonarqube-sdk.readthedocs.io/en/latest/quickstart Demonstrates how to authenticate with the SonarQube SDK using a token. This is the recommended method for secure access. It initializes the SonarQubeClient with the base URL and an API token. ```python from sonarqube import SonarQubeClient client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token" ) ``` -------------------------------- ### SonarQube SDK Quality Gate Status Check (Python) Source: https://sonarqube-sdk.readthedocs.io/en/latest/_sources/quickstart.rst Provides an example of how to retrieve the quality gate status for a given SonarQube project and check if it passed or failed. ```python status = client.qualitygates.project_status( project_key="my-project" ) if status.project_status.status == "OK": print("Quality gate passed!") else: print("Quality gate failed!") ``` -------------------------------- ### Authenticate with SonarQube SDK (Basic Auth) Source: https://sonarqube-sdk.readthedocs.io/en/latest/quickstart Illustrates how to authenticate with the SonarQube SDK using basic authentication with a username and password. This method is less secure than token authentication and should be used with caution. ```python from sonarqube import SonarQubeClient client = SonarQubeClient( base_url="https://sonarqube.example.com", username="admin", password="admin" ) ``` -------------------------------- ### Access SonarQube System API Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/client This code example shows how to interact with the System API to get the SonarQube server status, including its version. The `SystemAPI` is created on demand. This is helpful for monitoring the SonarQube instance. ```python >>> status = client.system.status() >>> print(f"SonarQube {status.version}") ``` -------------------------------- ### Get Server Base URL Setting Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Retrieves the server's base URL from SonarQube settings. This example demonstrates accessing the Settings API to fetch specific configuration values by their keys. ```python settings = client.settings.values(keys=["sonar.core.serverBaseURL"]) ``` -------------------------------- ### Install SonarQube SDK with uv Source: https://sonarqube-sdk.readthedocs.io/en/latest/_sources/index.rst Installs the SonarQube SDK using uv, a fast Python package installer and virtual environment manager. This is an alternative to pip for package management. ```bash uv add sonarqube-sdk ``` -------------------------------- ### Install SonarQube SDK with pip Source: https://sonarqube-sdk.readthedocs.io/en/latest/_sources/index.rst Installs the SonarQube SDK using pip, a package installer for Python. This is the standard method for adding Python packages to your environment. ```bash pip install sonarqube-sdk ``` -------------------------------- ### Initialize SonarQubeClient with Different Authentication Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/client Provides examples of initializing the SonarQubeClient using token authentication, basic authentication (username/password), and custom authentication handlers. ```python from sonarqube import SonarQubeClient # Token authentication client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token" ) # Basic authentication client = SonarQubeClient( base_url="https://sonarqube.example.com", username="admin", password="admin" ) # Custom authentication from sonarqube.auth import TokenAuth auth = TokenAuth(token="my-token") client = SonarQubeClient(base_url="https://sonarqube.example.com", auth=auth) ``` -------------------------------- ### Show SonarQube Application Details Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/applications Retrieves detailed information about a specific SonarQube application. This is a foundational operation often used to get the application object before performing other actions. The example shows how to access the application's name. ```python details = client.applications.show(application="my-app") print(details.application.name) ``` -------------------------------- ### GET /applications/show Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/applications Retrieves detailed information about a specific application. Requires 'Browse' permission. ```APIDOC ## GET /applications/show ### Description Retrieves detailed information about a specific application. Requires 'Browse' permission. ### Method GET ### Endpoint /applications/show ### Parameters #### Query Parameters - **application** (string) - Required - The key of the application to retrieve details for. - **branch** (string) - Optional - The name of the branch for which to retrieve application details. ### Request Example ``` GET /api/applications/show?application=my-app&branch=develop ``` ### Response #### Success Response (200) - **application** (object) - Contains application details, including its name. - **name** (string) - The name of the application. #### Response Example ```json { "application": { "key": "my-app", "name": "My Application", "qualifier": "APP", "revision": "1", "analysisDate": "2023-10-27T10:00:00+0000", "lastAnalysisDate": "2023-10-27T10:00:00+0000", "branch": "develop", "isMainBranch": false } } ``` ``` -------------------------------- ### SonarQubeClient Initialization and Authentication Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client This section details how to initialize the SonarQube client using different authentication methods and provides examples for token-based, basic, and custom authentication. ```APIDOC ## SonarQubeClient Initialization ### Description Initializes the SonarQube client. Supports various authentication methods including token, username/password, and custom authentication handlers. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Initialization Parameters * **base_url** (`str`) - Required - Base URL of the SonarQube instance. * **token** (`Optional[str]`) - Optional - API token for authentication. * **username** (`Optional[str]`) - Optional - Username for basic authentication. * **password** (`Optional[str]`) - Optional - Password for basic authentication. * **auth** (`Optional[BaseAuth]`) - Optional - Custom authentication handler. * **timeout** (`float`) - Optional - Request timeout in seconds (default: 30.0). * **verify_ssl** (`bool`) - Optional - Whether to verify SSL certificates (default: True). ### Raises * **ValueError** - If no authentication is provided or if username is provided without password. ### Examples #### Token Authentication ```python client = SonarQubeClient( base_url="https://sonarqube.example.com", token="squ_abcdef123456" ) ``` #### Basic Authentication ```python client = SonarQubeClient( base_url="https://sonarqube.example.com", username="admin", password="admin" ) ``` #### Custom Authentication ```python from sonarqube.auth import TokenAuth auth = TokenAuth(token="my-token") client = SonarQubeClient(base_url="https://sonarqube.example.com", auth=auth) ``` ``` -------------------------------- ### GET /license_usage Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/projects Retrieves license usage statistics for the SonarQube instance. Requires 'Administer System' permission. ```APIDOC ## GET /license_usage ### Description Retrieves license usage statistics for the SonarQube instance. Requires 'Administer System' permission. ### Method GET ### Endpoint /api/projects/license_usage ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```json null ``` ### Response #### Success Response (200) - **lines_of_code** (integer) - Total lines of code under license. - **expiration_date** (string) - License expiration date. #### Response Example ```json { "lines_of_code": 1000000, "expiration_date": "2024-12-31" } ``` ``` -------------------------------- ### Search Users Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Searches for users within SonarQube based on a query string. This example shows how to use the Users API to find users matching certain criteria. ```python users = client.users.search(q="john") ``` -------------------------------- ### Issue Search Example in Python Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/issues Demonstrates how to use the SonarQube SDK client to search for issues within a specific project and then iterate through the results to print the severity and message of each issue. ```python response = client.issues.search(project_keys=["my-project"]) for issue in response.issues: print(f"{issue.severity}: {issue.message}") ``` -------------------------------- ### Basic SonarQubeClient Initialization and Project Search Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Provides a basic example of initializing the SonarQubeClient and performing a project search. It iterates through the found components and prints their names. This illustrates direct access to API results. ```python from sonarqube import SonarQubeClient client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token" ) # Search for projects projects = client.projects.search(q="backend") for project in projects.components: print(project.name) ``` -------------------------------- ### Initialize and Use SonarQubeClient Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/client Demonstrates initializing the SonarQubeClient with token authentication, accessing the projects and issues APIs, and closing the client. It also shows how to use the client as a context manager. ```python from sonarqube import SonarQubeClient # Initialize with token authentication client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token" ) # Access API namespaces projects = client.projects.search(q="backend") issues = client.issues.search(project_keys=["my-project"]) # Close when done client.close() # Using as context manager:: with SonarQubeClient(base_url="...", token="...") as client: projects = client.projects.search() ``` -------------------------------- ### Initialize SonarQube Client with Basic Authentication Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client This example demonstrates initializing the SonarQube client using basic authentication with a username and password. It requires the SonarQube instance's base URL, username, and password. This method is convenient for manual access or when token management is not feasible. ```python client = SonarQubeClient( base_url="https://sonarqube.example.com", username="admin", password="admin" ) ``` -------------------------------- ### SonarQubeClient Initialization and Usage Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Demonstrates how to initialize the SonarQubeClient with token authentication and access different API namespaces. It also shows how to properly close the client or use it as a context manager. ```APIDOC ## SonarQubeClient Class ### Description The main client for interacting with the SonarQube API. This client provides access to all SonarQube API domains through namespace properties. Each namespace corresponds to an API domain (e.g., projects, issues, rules). ### Method `SonarQubeClient(base_url, token=None, username=None, password=None, auth=None, timeout=30.0, verify_ssl=True)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sonarqube import SonarQubeClient # Initialize with token authentication client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token" ) # Access API namespaces projects = client.projects.search(q="backend") issues = client.issues.search(project_keys=["my-project"]) # Close when done client.close() # Using as context manager: with SonarQubeClient(base_url="...", token="...") as client: projects = client.projects.search() ``` ### Response #### Success Response (Initialization) N/A (Client object is returned) #### Response Example (Accessing data) ```json { "components": [ { "id": "project-id-1", "name": "My Project", "key": "my-project-key", "qualities": {}, "measures": [] } ], "paging": { "page_index": 1, "page_size": 25, "total": 1 } } ``` #### Error Handling - **AuthenticationError**: If the provided token, username/password are invalid. - **ConnectionError**: If the base_url is unreachable or SSL verification fails. ``` -------------------------------- ### Create Project using SonarQube SDK Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/projects Provides an example of creating a new project via the SonarQube SDK. It shows how to call the `create` method on the projects client with the desired project name and key, and then prints the key of the newly created project from the `ProjectCreateResponse`. This requires an initialized SonarQube client. ```python >>> response = client.projects.create(name="My Project", project="my-project") >>> print(response.project.key) ``` -------------------------------- ### SonarQubeClient Initialization Parameters Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/client Illustrates the initialization of the SonarQubeClient, detailing its parameters such as base_url, token, username, password, auth, timeout, and verify_ssl. It also shows how the auth object is created internally. ```python from sonarqube import SonarQubeClient client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token", username="admin", password="admin", auth=None, timeout=10.0, verify_ssl=True, ) ``` -------------------------------- ### Initialize and Use SonarQubeClient with Token Authentication Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Demonstrates how to initialize the SonarQubeClient using token authentication and access API namespaces to search for projects and issues. The client must be closed after use. ```python from sonarqube import SonarQubeClient # Initialize with token authentication client = SonarQubeClient( base_url="https://sonarqube.example.com", token="your-token" ) # Access API namespaces projects = client.projects.search(q="backend") issues = client.issues.search(project_keys=["my-project"]) # Close when done client.close() ``` -------------------------------- ### GET /api/issues/authors Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/issues Get list of issue authors. Requires 'Browse' permission on the project. ```APIDOC ## GET /api/issues/authors ### Description Get list of issue authors. Requires 'Browse' permission on the project. ### Method GET ### Endpoint /api/issues/authors ### Parameters #### Query Parameters - **project** (string) - Required - Project key. - **ps** (integer) - Optional - Page size (max 100). - **q** (string) - Optional - Search query for author names. ### Response #### Success Response (200) - **authors** (array) - List of authors. #### Response Example ```json { "authors": [ "john", "jane" ] } ``` ``` -------------------------------- ### Initialize and Use SonarQubeClient as a Context Manager Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Shows how to use the SonarQubeClient within a `with` statement, which automatically handles the client's initialization and closing. This is a convenient way to manage the client's lifecycle. ```python with SonarQubeClient(base_url="...", token="...") as client: projects = client.projects.search() ``` -------------------------------- ### Get System Status Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Retrieves the current status and version information of the SonarQube server. This utilizes the System API to get operational details. ```python status = client.system.status() print(f"SonarQube {status.version}") ``` -------------------------------- ### Define SonarQube TextRange Model Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/issues Defines the TextRange model, representing a character range within a file for SonarQube issues. It includes start and end line numbers, and optional start and end character offsets. ```python from typing import Any, Optional, ClassVar from pydantic import ConfigDict from sonarqube.models.base import SonarQubeModel class TextRange(SonarQubeModel): """Text range within a file.""" start_line: int end_line: int start_offset: Optional[int] end_offset: Optional[int] model_config: ClassVar[ConfigDict] = {'extra': 'ignore', 'populate_by_name': True, 'str_strip_whitespace': True, 'use_enum_values': True, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True} ``` -------------------------------- ### Initialize SonarQube Client with Context Manager Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client This example illustrates initializing the SonarQube client using a context manager (`with` statement). This ensures that the client connection is properly closed and resources are released automatically upon exiting the block, even if errors occur. It requires the base URL and an authentication token. ```python with SonarQubeClient(base_url="...", token="...") as client: projects = client.projects.search() ``` -------------------------------- ### GET /api/rules/search Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/rules Searches for rules based on various criteria. ```APIDOC ## GET /api/rules/search ### Description Searches for rules based on various criteria. ### Method GET ### Endpoint /api/rules/search ### Parameters #### Query Parameters - **activation** (Optional[bool]) - Optional - Filter by activation status in quality profile. - **active_severities** (Optional[list[str]]) - Optional - Filter by active severities (e.g., ['MAJOR', 'CRITICAL']). - **asc** (Optional[bool]) - Optional - Ascending sort order. - **available_since** (Optional[str]) - Optional - Filter by availability date (YYYY-MM-DD). - **clean_code_attribute_categories** (Optional[list[str]]) - Optional - Clean code attribute categories. - **cwe** (Optional[list[str]]) - Optional - Filter by CWE identifiers (e.g., ['CWE-79']). - **f** (Optional[list[str]]) - Optional - Fields to return (e.g., ['key', 'name', 'severity']). - **facets** (Optional[list[str]]) - Optional - Facets to return (e.g., ['languages', 'types']). - **impact_severities** (Optional[list[str]]) - Optional - Impact severities. - **impact_software_qualities** (Optional[list[str]]) - Optional - Impact software qualities. - **include_external** (Optional[bool]) - Optional - Include external rules. - **inheritance** (Optional[list[str]]) - Optional - Filter by inheritance. - **is_template** (Optional[bool]) - Optional - Filter template rules. - **languages** (Optional[list[str]]) - Optional - Filter by languages (e.g., ['py', 'java']). - **owasp_top10** (Optional[list[str]]) - Optional - Filter by OWASP Top 10 2017 categories. - **owasp_top10_2021** (Optional[list[str]]) - Optional - Filter by OWASP Top 10 2021 categories. - **p** (Optional[int]) - Optional - Page number (default 1). - **ps** (Optional[int]) - Optional - Page size (default 100). - **q** (Optional[str]) - Optional - Search query for rule names or keys. - **qprofile** (Optional[str]) - Optional - Quality profile to search within. - **repositories** (Optional[list[str]]) - Optional - Filter by repository keys (e.g., ['python']). - **rule_key** (Optional[str]) - Optional - Exact match for rule key. - **s** (Optional[str]) - Optional - Sort field (e.g., 'name', 'severity'). - **sans_top25** (Optional[list[str]]) - Optional - Filter by SANS Top 25 categories. - **severities** (Optional[list[str]]) - Optional - Filter by severities (e.g., ['INFO', 'MINOR']). - **sonarsource_security** (Optional[list[str]]) - Optional - Filter by SonarSource security rules. - **statuses** (Optional[list[str]]) - Optional - Filter by rule status (e.g., ['READY', 'BETA']). - **tags** (Optional[list[str]]) - Optional - Filter by tags. - **template_key** (Optional[str]) - Optional - Filter by template rule key. - **types** (Optional[list[str]]) - Optional - Filter by rule types (e.g., ['CODE_SMELL', 'BUG']). ### Request Example ```python rules = client.rules.search( languages=["py"], severities=["MAJOR", "CRITICAL"], q="security" ) for rule in rules.rules: print(f"Key: {rule['key']}, Name: {rule['name']}, Severity: {rule['severity']}") ``` ### Response #### Success Response (200) - **rules** (list[Rule]) - A list of rules matching the search criteria. - **paging** (object) - Pagination information. - **components** (list[Component]) - List of components associated with the search results. - **effort_to_rule_correlation** (object) - Effort correlation data. - **metrics** (list[Metric]) - List of metrics. #### Response Example ```json { "rules": [ { "key": "python:S100", "name": "Use tuples instead of lists for multi-value return.", "type": "CODE_SMELL", "severity": "INFO", "createdAt": "2009-09-01T10:00:00+0200", "updatedAt": "2023-01-01T10:00:00+0200" } ], "paging": { "pageIndex": 1, "pageSize": 100, "total": 500 } } ``` ``` -------------------------------- ### Initialize SonarQube Client with Token Authentication Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client This example shows how to initialize the SonarQube client using an API token for authentication. It requires the base URL of the SonarQube instance and the authentication token. This method is suitable for automated processes where tokens can be securely managed. ```python client = SonarQubeClient( base_url="https://sonarqube.example.com", token="squ_abcdef123456" ) ``` -------------------------------- ### GET /api/rules/repositories Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/rules Lists rule repositories available in SonarQube. ```APIDOC ## GET /api/rules/repositories ### Description Lists rule repositories available in SonarQube. ### Method GET ### Endpoint /api/rules/repositories ### Parameters #### Query Parameters - **language** (Optional[str]) - Optional - Filter by language (e.g., 'py', 'java'). - **q** (Optional[str]) - Optional - Search query for repository name. ### Request Example ```python repos = client.rules.repositories(language="py") for repo in repos.repositories: print(repo) ``` ### Response #### Success Response (200) - **repositories** (list[RuleRepository]) - A list of rule repositories. #### Response Example ```json { "repositories": [ { "key": "python", "name": "Python Rules", "language": "py" }, { "key": "javascript", "name": "JavaScript Rules", "language": "js" } ] } ``` ``` -------------------------------- ### Initialize SonarQube Client with Custom Authentication Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client This example shows how to initialize the SonarQube client with a custom authentication handler, specifically using `TokenAuth`. This provides flexibility for advanced authentication scenarios. It requires the base URL and an instance of the custom authentication object. ```python from sonarqube.auth import TokenAuth auth = TokenAuth(token="my-token") client = SonarQubeClient(base_url="https://sonarqube.example.com", auth=auth) ``` -------------------------------- ### GET /qualityprofiles/search Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/qualityprofiles Searches for quality profiles based on specified criteria. ```APIDOC ## GET /qualityprofiles/search ### Description Searches for quality profiles based on specified criteria. ### Method GET ### Endpoint /api/qualityprofiles/search ### Parameters #### Path Parameters None #### Query Parameters - **defaults** (boolean) - Optional - Filter by default profiles (true/false). - **language** (string) - Optional - Filter by language key. - **project** (string) - Optional - Filter by project key. - **quality_profile** (string) - Optional - Filter by quality profile name. #### Request Body None ### Request Example ``` GET /api/qualityprofiles/search?language=py ``` ### Response #### Success Response (200) - **profiles** (array) - List of matching quality profiles. - **name** (string) - Quality profile name. - **language** (string) - Language key. - **key** (string) - Quality profile key. - **isDefault** (boolean) - Indicates if it's a default profile. - **isInheritance** (boolean) - Indicates if inheritance is enabled. - **paging** (object) - Pagination information. - **pageIndex** (integer) - Current page index. - **pageSize** (integer) - Page size. - **total** (integer) - Total number of profiles found. #### Response Example ```json { "profiles": [ { "name": "Sonar Way", "language": "py", "key": "py-sonarway-12345", "isDefault": true, "isInheritance": false } ], "paging": { "pageIndex": 1, "pageSize": 50, "total": 1 } } ``` ``` -------------------------------- ### Initialize and Close SonarQubeClient Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/client Demonstrates how to initialize the SonarQubeClient with a base URL and token, and how to properly close the client to release resources. The client can also be used as a context manager. ```python from sonarqube import SonarQubeClient # Initialize client client = SonarQubeClient(base_url="...", token="...") # Use client (example: access issues API) # issues = client.issues.search(project_keys=["my-project"], severities=["CRITICAL"]) # Close the client to release resources client.close() # Using as a context manager with SonarQubeClient(base_url="...", token="...") as client: # ... use client ... pass # client is automatically closed on exit ``` -------------------------------- ### GET /qualityprofiles/inheritance Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/qualityprofiles Retrieves inheritance information for a specific quality profile. ```APIDOC ## GET /qualityprofiles/inheritance ### Description Retrieves inheritance information for a specific quality profile. ### Method GET ### Endpoint /api/qualityprofiles/inheritance ### Parameters #### Path Parameters None #### Query Parameters - **language** (string) - Required - Language key of the quality profile. - **quality_profile** (string) - Required - Name of the quality profile. #### Request Body None ### Request Example ``` GET /api/qualityprofiles/inheritance?language=py&qualityProfile=My%20Profile ``` ### Response #### Success Response (200) - **inheritance** (object) - Object containing inheritance details. - **isInheritance** (boolean) - Indicates if inheritance is enabled. - **inherited** (boolean) - Indicates if the profile is inherited. - **parent** (string) - Name of the parent profile if inherited. #### Response Example ```json { "isInheritance": false, "inherited": false, "parent": null } ``` ``` -------------------------------- ### GET /changelog Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/issues Retrieves the changelog for a specific issue, detailing all the changes made to it over time. ```APIDOC ## GET /changelog ### Description Retrieves the changelog for a specific issue, detailing all the changes made to it over time. ### Method GET ### Endpoint /api/issues/changelog ### Parameters #### Query Parameters - **issue** (str) - Required - The key of the issue for which to retrieve the changelog. ### Request Example ```json { "issue": "AXoN-12345" } ``` ### Response #### Success Response (200) - **changelog** (list[dict]) - A list of changelog entries, each containing details about a change. - **creationDate** (str) - The date and time the change was made. - **user** (str) - The user who made the change. - **change** (str) - A description of the change. #### Response Example ```json { "changelog": [ { "creationDate": "2023-10-27T10:00:00+0000", "user": "john.doe", "change": "Severity changed from BLOCKER to CRITICAL" }, { "creationDate": "2023-10-27T10:05:00+0000", "user": "jane.smith", "change": "Comment added" } ] } ``` ``` -------------------------------- ### GET /search_inherited_rules Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/qualityprofiles Searches for rules inherited by a quality profile. Requires 'Browse' permission. ```APIDOC ## GET /search_inherited_rules ### Description Search for rules inherited by a quality profile. ### Method GET ### Endpoint /api/qualityprofiles/search_inherited_rules ### Parameters #### Query Parameters - **profile_key** (string) - Required - Quality profile key. - **language** (string) - Optional - Filter by language. - **p** (integer) - Optional - Page number. - **ps** (integer) - Optional - Page size. - **query** (string) - Optional - Search query string for rules. - **severities** (string) - Optional - Comma-separated list of severity levels. - **types** (string) - Optional - Comma-separated list of rule types. ### Request Example ```json { "profile_key": "my-profile-key", "severities": "BLOCKER,CRITICAL" } ``` ### Response #### Success Response (200) - **paging** (object) - Pagination information. - **page** (integer) - Current page number. - **pageSize** (integer) - Number of items per page. - **total** (integer) - Total number of rules found. - **rules** (array) - List of inherited rules. - **key** (string) - Key of the rule. - **name** (string) - Name of the rule. - **severity** (string) - Severity of the rule. - **type** (string) - Type of the rule. - **repo** (string) - Repository the rule belongs to. #### Response Example ```json { "paging": { "page": 1, "pageSize": 25, "total": 5 }, "rules": [ { "key": "java:S100", "name": "Methods should not be too complex.", "severity": "MAJOR", "type": "CODE_SMELL", "repo": "java-security" } ] } ``` #### Error Response (400/403/404) - **error** (string) - Error message. - **status** (integer) - Error status code. ``` -------------------------------- ### Create and Manage SonarQube Applications (Python) Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/applications This snippet demonstrates how to use the SonarQube SDK to create a new application, add a project to it, and manage application settings. It requires the SonarQubeClient to be initialized with a base URL and an authentication token. The primary outputs are the created application object and confirmation of project addition. ```python from sonarqube import SonarQubeClient client = SonarQubeClient(base_url="...", token="...") # Create an application app = client.applications.create( name="My Application", key="my-app", visibility="private" ) # Add a project to the application client.applications.add_project(application="my-app", project="my-project") ``` ```python # Create an application app = client.applications.create(name="My Application", key="my-app") # Add a project client.applications.add_project(application="my-app", project="my-project") ``` -------------------------------- ### QualityGates API - Get Project Status Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Retrieves the quality gate status for a specific project. ```APIDOC ## QualityGates API - Get Project Status ### Description Retrieves the current quality gate status for a specified SonarQube project. ### Method `client.qualitygates.project_status` ### Endpoint (Internal API, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters * **project_key** (`str`) - Required - The key of the project for which to get the quality gate status. ### Request Body None ### Request Example ```python status = client.qualitygates.project_status(project_key="my-project") print(status.project_status.status) ``` ### Response #### Success Response (200) * **project_status** (`object`) - An object containing the project's quality gate status. * **status** (`str`) - The status of the quality gate (e.g., "OK", "ERROR"). #### Response Example ```json { "project_status": { "status": "OK", "conditions": [ { "metric": "coverage", "op": ">=", "errorValue": "80", "actualValue": "85.5" } ] } } ``` ``` -------------------------------- ### Access SonarQube Applications API Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client This snippet demonstrates accessing the Applications API to manage SonarQube applications. It shows an example of creating a new application with a specified name and key. The `ApplicationsAPI` instance provides methods for application lifecycle management. ```python app = client.applications.create(name="My Application", key="my-app") ``` -------------------------------- ### GET /qualitygates/list Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/qualitygates Fetches a list of all available quality gates within the SonarQube instance. ```APIDOC ## GET /qualitygates/list ### Description Retrieves a comprehensive list of all quality gates configured within the SonarQube instance. This is useful for understanding available gates and their configurations. ### Method GET ### Endpoint /api/qualitygates/list ### Parameters (No parameters required) ### Request Example (No request body) ### Response #### Success Response (200) - **qualitygates** (array) - A list of quality gate objects, each containing details like name, id, and conditions. #### Response Example ```json { "qualitygates": [ { "name": "Sonar way", "id": "AV4fJ4R-L91f3Qyv27Qh", "default": true, "conditions": [ { "metric": "bugs", "op": "gt", "error": "0", "warning": "0" } ] }, { "name": "My Quality Gate", "id": "AV4fJ4R-L91f3Qyv27Qx", "default": false, "conditions": [ { "metric": "vulnerabilities", "op": "gt", "error": "0", "warning": "0" } ] } ] } ``` ``` -------------------------------- ### Applications API - Create Application Source: https://sonarqube-sdk.readthedocs.io/en/latest/api/client Creates a new application in SonarQube. ```APIDOC ## Applications API - Create Application ### Description Creates a new application within SonarQube. Requires a name and a unique key for the application. ### Method `client.applications.create` ### Endpoint (Internal API, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters * **name** (`str`) - Required - The display name for the new application. * **key** (`str`) - Required - A unique key for the new application. ### Request Body None ### Request Example ```python app = client.applications.create(name="My Application", key="my-app") ``` ### Response #### Success Response (200) * **application** (`object`) - An object representing the newly created application. * Contains details like `name`, `key`, `creationDate`, etc. #### Response Example ```json { "application": { "key": "my-app", "name": "My Application", "creationDate": "2023-10-27T10:00:00+0000" } } ``` ``` -------------------------------- ### GET /export_findings Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/projects Exports all findings for a given project. Requires 'Browse' permission on the project. ```APIDOC ## GET /export_findings ### Description Exports all findings for a given project. Requires 'Browse' permission on the project. ### Method GET ### Endpoint /api/projects/export_findings ### Parameters #### Path Parameters None #### Query Parameters - **project** (string) - Required - Project key. - **branch** (string) - Optional - Branch name. - **pull_request** (string) - Optional - Pull request ID. ### Request Example ```json { "project": "my-project", "branch": "main", "pull_request": "123" } ``` ### Response #### Success Response (200) - **findings** (object) - Response containing exported findings. #### Response Example ```json { "findings": [ { "key": "123", "ruleKey": "S1186", "severity": "MAJOR", "type": "CODE_SMELL", "effort": 0.5, "line": 10, "flows": [], "status": "OPEN", "resolution": "FIXED", "message": "This block is dead code.", "component": "my-project:src/main/java/com/example/MyClass.java" } ] } ``` ``` -------------------------------- ### GET /search Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/qualityprofiles Searches for quality profiles based on various criteria. Requires 'Browse' permission. ```APIDOC ## GET /search ### Description Search for quality profiles. ### Method GET ### Endpoint /api/qualityprofiles/search ### Parameters #### Query Parameters - **language** (string) - Optional - Filter by language. - **p** (integer) - Optional - Page number. - **ps** (integer) - Optional - Page size. - **q** (string) - Optional - Search query string. - **qualifier** (string) - Optional - Filter by profile qualifier (e.g., 'TRK' for project). - **sortField** (string) - Optional - Field to sort by (e.g., 'name', 'creationDate'). - **ascending** (boolean) - Optional - Sorting order (true for ascending, false for descending). ### Request Example ```json { "language": "py", "q": "My Profile" } ``` ### Response #### Success Response (200) - **paging** (object) - Pagination information. - **page** (integer) - Current page number. - **pageSize** (integer) - Number of items per page. - **total** (integer) - Total number of profiles found. - **profiles** (array) - List of quality profiles matching the search criteria. - **key** (string) - Key of the profile. - **name** (string) - Name of the profile. - **language** (string) - Language of the profile. - **isDefault** (boolean) - Whether the profile is the default. - **isTemplate** (boolean) - Whether the profile is a template. #### Response Example ```json { "paging": { "page": 1, "pageSize": 25, "total": 10 }, "profiles": [ { "key": "my-profile-key", "name": "My Profile", "language": "py", "isDefault": false, "isTemplate": false } ] } ``` #### Error Response (400/403/404) - **error** (string) - Error message. - **status** (integer) - Error status code. ``` -------------------------------- ### GET /tags Source: https://sonarqube-sdk.readthedocs.io/en/latest/_modules/sonarqube/api/issues Retrieves a list of issue tags for a given project. Requires 'Browse' permission on the project. ```APIDOC ## GET /tags ### Description Retrieves a list of issue tags for a given project. Requires 'Browse' permission on the project. ### Method GET ### Endpoint /api/issues/tags ### Parameters #### Path Parameters - None #### Query Parameters - **project** (string) - Optional - Project key. - **ps** (integer) - Optional - Page size (max 100). - **q** (string) - Optional - Search query for tags. ### Request Example ```json { "project": "my-project", "ps": 50, "q": "security" } ``` ### Response #### Success Response (200) - **tags** (list[object]) - A list of tag objects, each potentially containing tag details. #### Response Example ```json { "tags": [ { "name": "security", "count": 150 }, { "name": "bug", "count": 75 } ] } ``` ```