---
title: Get per-file code coverage data
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: Docs > API Reference > Code Coverage
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Get per-file code coverage data{% #get-per-file-code-coverage-data %}
Copy pageCopied
{% tab title="v2" %}

| Datadog site      | API endpoint                                                  |
| ----------------- | ------------------------------------------------------------- |
| ap1.datadoghq.com | POST https://api.ap1.datadoghq.com/api/v2/code-coverage/files |
| ap2.datadoghq.com | POST https://api.ap2.datadoghq.com/api/v2/code-coverage/files |
| app.datadoghq.eu  | POST https://api.datadoghq.eu/api/v2/code-coverage/files      |
| app.ddog-gov.com  | POST https://api.ddog-gov.com/api/v2/code-coverage/files      |
| us2.ddog-gov.com  | POST https://api.us2.ddog-gov.com/api/v2/code-coverage/files  |
| uk1.datadoghq.com | POST https://api.uk1.datadoghq.com/api/v2/code-coverage/files |
| app.datadoghq.com | POST https://api.datadoghq.com/api/v2/code-coverage/files     |
| us3.datadoghq.com | POST https://api.us3.datadoghq.com/api/v2/code-coverage/files |
| us5.datadoghq.com | POST https://api.us5.datadoghq.com/api/v2/code-coverage/files |

### Overview

Retrieve per-file code coverage data for a specific commit, branch, or pull request. Exactly one of `commit_sha`, `branch`, or `pr_number` must be provided. Optionally filter by `service`, `codeowner`, or `flag` (at most one). This endpoint requires the `code_coverage_read` permission.

OAuth apps require the `code_coverage_read` authorization [scope](https://docs.datadoghq.com/api/latest/scopes.md#code-coverage) to access this endpoint.



### Request

#### Body Data (required)



{% tab title="Model" %}

| Parent field | Field                        | Type    | Description                                                                                                                                                                                      |
| ------------ | ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|              | data [*required*]       | object  | Data object for files coverage request.                                                                                                                                                          |
| data         | attributes [*required*] | object  | Attributes for requesting per-file code coverage data. Exactly one of `commit_sha`, `branch`, or `pr_number` must be provided. At most one of `service`, `codeowner`, or `flag` may be provided. |
| attributes   | branch                       | string  | The branch name.                                                                                                                                                                                 |
| attributes   | changed_only                 | boolean | When true, return coverage data only for files that were changed in the specified scope.                                                                                                         |
| attributes   | codeowner                    | string  | Filter coverage by code owner. At most one of `service`, `codeowner`, or `flag` may be provided.                                                                                                 |
| attributes   | commit_sha                   | string  | The commit SHA (40-character hexadecimal string).                                                                                                                                                |
| attributes   | flag                         | string  | Filter coverage by coverage flag. At most one of `service`, `codeowner`, or `flag` may be provided.                                                                                              |
| attributes   | pr_number                    | int64   | The pull request number. Must be a positive integer.                                                                                                                                             |
| attributes   | repository_id                | string  | **DEPRECATED**: Deprecated: use `repository_url` instead. The repository URL.                                                                                                                    |
| attributes   | repository_url               | string  | The repository URL. Accepts a full URL with or without a scheme (for example, `https://github.com/org/repo` or `github.com/org/repo`).                                                           |
| attributes   | service                      | string  | Filter coverage by service name. At most one of `service`, `codeowner`, or `flag` may be provided.                                                                                               |
| data         | type [*required*]       | enum    | JSON:API type for files coverage request. The value must always be `ci_app_coverage_files_request`. Allowed enum values: `ci_app_coverage_files_request`                                         |

{% /tab %}

{% tab title="Example" %}

```json
{
  "data": {
    "attributes": {
      "branch": "main",
      "changed_only": true,
      "codeowner": "@my-team",
      "commit_sha": "66adc9350f2cc9b250b69abddab733dd55e1a588",
      "flag": "unit-tests",
      "pr_number": 42,
      "repository_id": "github.com/datadog/shopist",
      "repository_url": "https://github.com/datadog/shopist",
      "service": "my-service"
    },
    "type": "ci_app_coverage_files_request"
  }
}
```

{% /tab %}

### Response

{% tab title="200" %}
OK
{% tab title="Model" %}
Response object containing per-file code coverage data.

| Parent field         | Field            | Type      | Description                                                                                                                               |
| -------------------- | ---------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
|                      | data             | object    | Data object for files coverage response.                                                                                                  |
| data                 | attributes       | object    | Attributes of the per-file code coverage response.                                                                                        |
| attributes           | base_commit_sha  | string    | The SHA of the base commit used for comparison (for example, the merge base for a PR).                                                    |
| attributes           | event_timestamp  | int64     | Unix timestamp (milliseconds) of the coverage event.                                                                                      |
| attributes           | files            | object    | Map of file paths to per-file coverage line data.                                                                                         |
| additionalProperties | <any-key>        | object    | Per-file line coverage data including executable, covered, and added lines.                                                               |
| <any-key>            | added_lines      | [integer] | Line numbers that were added in the specified scope (for example, in a PR diff).                                                          |
| <any-key>            | covered_lines    | [integer] | Line numbers that were covered by tests.                                                                                                  |
| <any-key>            | executable_lines | [integer] | Line numbers that are executable (can be covered).                                                                                        |
| attributes           | head_commit_sha  | string    | The SHA of the head commit for which coverage was evaluated.                                                                              |
| attributes           | report_count     | int64     | Number of coverage reports evaluated.                                                                                                     |
| data                 | id               | string    | Unique identifier for the files coverage response.                                                                                        |
| data                 | type             | enum      | JSON:API type for files coverage response. The value must always be `ci_app_coverage_files`. Allowed enum values: `ci_app_coverage_files` |

{% /tab %}

{% tab title="Example" %}

```json
{
  "data": {
    "attributes": {
      "base_commit_sha": "abc1234567890abcdef1234567890abcdef12345",
      "event_timestamp": 1709564000000,
      "files": {
        "<any-key>": {
          "added_lines": [
            11,
            12
          ],
          "covered_lines": [
            10,
            11,
            15
          ],
          "executable_lines": [
            10,
            11,
            12,
            15,
            20
          ]
        }
      },
      "head_commit_sha": "66adc9350f2cc9b250b69abddab733dd55e1a588",
      "report_count": 3
    },
    "id": "ZGQxMjM0NV9tYWluXzE3MDk1NjQwMDA=",
    "type": "ci_app_coverage_files"
  }
}
```

{% /tab %}

{% /tab %}

{% tab title="400" %}
Bad Request
{% tab title="Model" %}
API error response.

| Field                    | Type     | Description       |
| ------------------------ | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |

{% /tab %}

{% tab title="Example" %}

```json
{
  "errors": [
    "Bad Request"
  ]
}
```

{% /tab %}

{% /tab %}

{% tab title="403" %}
Not Authorized
{% tab title="Model" %}
API error response.

| Field                    | Type     | Description       |
| ------------------------ | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |

{% /tab %}

{% tab title="Example" %}

```json
{
  "errors": [
    "Bad Request"
  ]
}
```

{% /tab %}

{% /tab %}

{% tab title="404" %}
Not Found
{% tab title="Model" %}
API error response.

| Field                    | Type     | Description       |
| ------------------------ | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |

{% /tab %}

{% tab title="Example" %}

```json
{
  "errors": [
    "Bad Request"
  ]
}
```

{% /tab %}

{% /tab %}

{% tab title="429" %}
Too many requests
{% tab title="Model" %}
API error response.

| Field                    | Type     | Description       |
| ------------------------ | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |

{% /tab %}

{% tab title="Example" %}

```json
{
  "errors": [
    "Bad Request"
  ]
}
```

{% /tab %}

{% /tab %}

{% tab title="500" %}
Internal server error
{% tab title="Model" %}
API error response.

| Field                    | Type     | Description       |
| ------------------------ | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |

{% /tab %}

{% tab title="Example" %}

```json
{
  "errors": [
    "Bad Request"
  ]
}
```

{% /tab %}

{% /tab %}

### Code Example

##### 
                  \## default
# 
 \# Use a Personal Access Token or Service Access Token export DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>"  \# Curl command curl -X POST "https://api.datadoghq.com/api/v2/code-coverage/files" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DD_BEARER_TOKEN}" \
-d @- << EOF
{
  "data": {
    "attributes": {
      "changed_only": true,
      "commit_sha": "66adc9350f2cc9b250b69abddab733dd55e1a588",
      "repository_url": "https://github.com/datadog/test-service"
    },
    "type": "ci_app_coverage_files_request"
  }
}
EOF 
                
##### 

```python
"""
Get per-file code coverage data returns "OK" response
"""

from os import environ
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.code_coverage_api import CodeCoverageApi
from datadog_api_client.v2.model.files_coverage_request import FilesCoverageRequest
from datadog_api_client.v2.model.files_coverage_request_attributes import FilesCoverageRequestAttributes
from datadog_api_client.v2.model.files_coverage_request_data import FilesCoverageRequestData
from datadog_api_client.v2.model.files_coverage_request_type import FilesCoverageRequestType

body = FilesCoverageRequest(
    data=FilesCoverageRequestData(
        attributes=FilesCoverageRequestAttributes(
            changed_only=True,
            commit_sha="66adc9350f2cc9b250b69abddab733dd55e1a588",
            repository_url="https://github.com/datadog/shopist",
        ),
        type=FilesCoverageRequestType.CI_APP_COVERAGE_FILES_REQUEST,
    ),
)

configuration = Configuration()
configuration.access_token = environ["DD_BEARER_TOKEN"]
with ApiClient(configuration) as api_client:
    api_instance = CodeCoverageApi(api_client)
    response = api_instance.get_code_coverage_files(body=body)

    print(response)
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=python) and then save the example to `example.py` and run following commands:
    DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" python3 "example.py"
##### 

```ruby
# Get per-file code coverage data returns "OK" response

require "datadog_api_client"
DatadogAPIClient.configure do |config|
  config.access_token = ENV["DD_BEARER_TOKEN"]
end
api_instance = DatadogAPIClient::V2::CodeCoverageAPI.new

body = DatadogAPIClient::V2::FilesCoverageRequest.new({
  data: DatadogAPIClient::V2::FilesCoverageRequestData.new({
    attributes: DatadogAPIClient::V2::FilesCoverageRequestAttributes.new({
      changed_only: true,
      commit_sha: "66adc9350f2cc9b250b69abddab733dd55e1a588",
      repository_url: "https://github.com/datadog/shopist",
    }),
    type: DatadogAPIClient::V2::FilesCoverageRequestType::CI_APP_COVERAGE_FILES_REQUEST,
  }),
})
p api_instance.get_code_coverage_files(body)
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=ruby) and then save the example to `example.rb` and run following commands:
    DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" rb "example.rb"
##### 

```go
// Get per-file code coverage data returns "OK" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
)

func main() {
	body := datadogV2.FilesCoverageRequest{
		Data: datadogV2.FilesCoverageRequestData{
			Attributes: datadogV2.FilesCoverageRequestAttributes{
				ChangedOnly:   datadog.PtrBool(true),
				CommitSha:     datadog.PtrString("66adc9350f2cc9b250b69abddab733dd55e1a588"),
				RepositoryUrl: datadog.PtrString("https://github.com/datadog/shopist"),
			},
			Type: datadogV2.FILESCOVERAGEREQUESTTYPE_CI_APP_COVERAGE_FILES_REQUEST,
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	ctx = context.WithValue(ctx, datadog.ContextAccessToken, os.Getenv("DD_BEARER_TOKEN"))
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewCodeCoverageApi(apiClient)
	resp, r, err := api.GetCodeCoverageFiles(ctx, body)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `CodeCoverageApi.GetCodeCoverageFiles`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `CodeCoverageApi.GetCodeCoverageFiles`:\n%s\n", responseContent)
}
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=go) and then save the example to `main.go` and run following commands:
    DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" go run "main.go"
##### 

```java
// Get per-file code coverage data returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v2.api.CodeCoverageApi;
import com.datadog.api.client.v2.model.FilesCoverageRequest;
import com.datadog.api.client.v2.model.FilesCoverageRequestAttributes;
import com.datadog.api.client.v2.model.FilesCoverageRequestData;
import com.datadog.api.client.v2.model.FilesCoverageRequestType;
import com.datadog.api.client.v2.model.FilesCoverageResponse;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    defaultClient.setAccessToken(System.getenv("DD_BEARER_TOKEN"));
    CodeCoverageApi apiInstance = new CodeCoverageApi(defaultClient);

    FilesCoverageRequest body =
        new FilesCoverageRequest()
            .data(
                new FilesCoverageRequestData()
                    .attributes(
                        new FilesCoverageRequestAttributes()
                            .changedOnly(true)
                            .commitSha("66adc9350f2cc9b250b69abddab733dd55e1a588")
                            .repositoryUrl("https://github.com/datadog/shopist"))
                    .type(FilesCoverageRequestType.CI_APP_COVERAGE_FILES_REQUEST));

    try {
      FilesCoverageResponse result = apiInstance.getCodeCoverageFiles(body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling CodeCoverageApi#getCodeCoverageFiles");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=java) and then save the example to `Example.java` and run following commands:
    DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" java "Example.java"
##### 

```rust
// Get per-file code coverage data returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_code_coverage::CodeCoverageAPI;
use datadog_api_client::datadogV2::model::FilesCoverageRequest;
use datadog_api_client::datadogV2::model::FilesCoverageRequestAttributes;
use datadog_api_client::datadogV2::model::FilesCoverageRequestData;
use datadog_api_client::datadogV2::model::FilesCoverageRequestType;

#[tokio::main]
async fn main() {
    let body = FilesCoverageRequest::new(FilesCoverageRequestData::new(
        FilesCoverageRequestAttributes::new()
            .changed_only(true)
            .commit_sha("66adc9350f2cc9b250b69abddab733dd55e1a588".to_string())
            .repository_url("https://github.com/datadog/shopist".to_string()),
        FilesCoverageRequestType::CI_APP_COVERAGE_FILES_REQUEST,
    ));
    let configuration = datadog::Configuration::new();
    let api = CodeCoverageAPI::with_config(configuration);
    let resp = api.get_code_coverage_files(body).await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=rust) and then save the example to `src/main.rs` and run following commands:
    DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
##### 

```typescript
/**
 * Get per-file code coverage data returns "OK" response
 */

import { client, v2 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration({
  authMethods: {
    AuthZ: {
      accessToken: process.env.DD_BEARER_TOKEN as string,
    },
  },
});
const apiInstance = new v2.CodeCoverageApi(configuration);

const params: v2.CodeCoverageApiGetCodeCoverageFilesRequest = {
  body: {
    data: {
      attributes: {
        changedOnly: true,
        commitSha: "66adc9350f2cc9b250b69abddab733dd55e1a588",
        repositoryUrl: "https://github.com/datadog/shopist",
      },
      type: "ci_app_coverage_files_request",
    },
  },
};

apiInstance
  .getCodeCoverageFiles(params)
  .then((data: v2.FilesCoverageResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=typescript) and then save the example to `example.ts` and run following commands:
    DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" tsc "example.ts"
{% /tab %}
