REST Resources Provided By: Bitbucket Server - Code Insights

This is the reference document for the Atlassian Bitbucket REST API. The REST API is for developers who want to:

You can read more about developing Bitbucket plugins in the Bitbucket Developer Documentation.

Getting started

Because the REST API is based on open standards, you can use any web development language or command line tool capable of generating an HTTP request to access the API. See the developer documentation for a basic usage example.

If you're already working with the Atlassian SDK, the REST API Browser is a great tool for exploring and experimenting with the Bitbucket REST API.

Structure of the REST URIs

Bitbucket's REST APIs provide access to resources (data entities) via URI paths. To use a REST API, your application will make an HTTP request and parse the response. The Bitbucket REST API uses JSON as its communication format, and the standard HTTP methods like GET, PUT, POST and DELETE. URIs for Bitbucket's REST API resource have the following structure:

    http://host:port/context/rest/api-name/api-version/path/to/resource

For example, the following URI would retrieve a page of the latest commits to the jira repository in the Jira project on https://stash.atlassian.com.

    https://stash.atlassian.com/rest/api/1.0/projects/JIRA/repos/jira/commits

See the API descriptions below for a full list of available resources.

Alternatively we also publish a list of resources in WADL format. It is available here.

Paged APIs

Bitbucket uses paging to conserve server resources and limit response size for resources that return potentially large collections of items. A request to a paged API will result in a values array wrapped in a JSON object with some paging metadata, like this:

    {
        "size": 3,
        "limit": 3,
        "isLastPage": false,
        "values": [
            { /* result 0 */ },
            { /* result 1 */ },
            { /* result 2 */ }
        ],
        "start": 0,
        "filter": null,
        "nextPageStart": 3
    }

Clients can use the limit and start query parameters to retrieve the desired number of results.

The limit parameter indicates how many results to return per page. Most APIs default to returning 25 if the limit is left unspecified. This number can be increased, but note that a resource-specific hard limit will apply. These hard limits can be configured by server administrators, so it's always best practice to check the limit attribute on the response to see what limit has been applied. The request to get a larger page should look like this:

    http://host:port/context/rest/api-name/api-version/path/to/resource?limit={desired size of page}

For example:

    https://stash.atlassian.com/rest/api/1.0/projects/JIRA/repos/jira/commits?limit=1000

The start parameter indicates which item should be used as the first item in the page of results. All paged responses contain an isLastPage attribute indicating whether another page of items exists.

Important: If more than one page exists (i.e. the response contains "isLastPage": false), the response object will also contain a nextPageStart attribute which must be used by the client as the start parameter on the next request. Identifiers of adjacent objects in a page may not be contiguous, so the start of the next page is not necessarily the start of the last page plus the last page's size. A client should always use nextPageStart to avoid unexpected results from a paged API. The request to get a subsequent page should look like this:

    http://host:port/context/rest/api-name/api-version/path/to/resource?start={nextPageStart from previous response}

For example:

    https://stash.atlassian.com/rest/api/1.0/projects/JIRA/repos/jira/commits?start=25

Authentication

Any authentication that works against Bitbucket will work against the REST API. The preferred authentication methods are HTTP Basic (when using SSL) and OAuth. Other supported methods include: HTTP Cookies and Trusted Applications.

You can find OAuth code samples in several programming languages at bitbucket.org/atlassian_tutorial/atlassian-oauth-examples.

The log-in page uses cookie-based authentication, so if you are using Bitbucket in a browser you can call REST from JavaScript on the page and rely on the authentication that the browser has established.

Errors & Validation

If a request fails due to client error, the resource will return an HTTP response code in the 40x range. These can be broadly categorised into:

HTTP Code Description
400 (Bad Request) One or more of the required parameters or attributes:
  • were missing from the request;
  • incorrectly formatted; or
  • inappropriate in the given context.
401 (Unauthorized) Either:
  • Authentication is required but was not attempted.
  • Authentication was attempted but failed.
  • Authentication was successful but the authenticated user does not have the requisite permission for the resource.
See the individual resource documentation for details of required permissions.
403 (Forbidden) Actions are usually "forbidden" if they involve breaching the licensed user limit of the server, or degrading the authenticated user's permission level. See the individual resource documentation for more details.
404 (Not Found) The entity you are attempting to access, or the project or repository containing it, does not exist.
405 (Method Not Allowed) The request HTTP method is not appropriate for the targeted resource. For example an HTTP GET to a resource that only accepts an HTTP POST will result in a 405.
409 (Conflict) The attempted update failed due to some conflict with an existing resource. For example:
  • Creating a project with a key that already exists
  • Merging an out-of-date pull request
  • Deleting a comment that has replies
  • etc.
See the individual resource documentation for more details.
415 (Unsupported Media Type) The request entity has a Content-Type that the server does not support. Almost all of the Bitbucket REST API accepts application/json format, but check the individual resource documentation for more details. Additionally, double-check that you are setting the Content-Type header correctly on your request (e.g. using -H "Content-Type: application/json" in cURL).

For 400 HTTP codes the response will typically contain one or more validation error messages, for example:

    {
        "errors": [
            {
                "context": "name",
                "message": "The name should be between 1 and 255 characters.",
                "exceptionName": null
            },
            {
                "context": "email",
                "message": "The email should be a valid email address.",
                "exceptionName": null
            }
        ]
    }
    

The context attribute indicates which parameter or request entity attribute failed validation. Note that the context may be null.

For 401, 403, 404 and 409 HTTP codes, the response will contain one or more descriptive error messages:

    {
        "errors": [
            {
                "context": null,
                "message": "A detailed error message.",
                "exceptionName": null
            }
        ]
    }
    

A 500 (Server Error) HTTP code indicates an incorrect resource url or an unexpected server error. Double-check the URL you are trying to access, then report the issue to your server administrator or Atlassian Support if problems persist.

Personal Repositories

Bitbucket allows users to manage their own repositories, called personal repositories. These are repositories associated with the user and to which they always have REPO_ADMIN permission.

Accessing personal repositories via REST is achieved through the normal project-centric REST URLs using the user's slug prefixed by tilde as the project key. E.g. to list personal repositories for a user with slug "johnsmith" you would make a GET to:

http://example.com/rest/api/1.0/projects/~johnsmith/repos

In addition to this, Bitbucket allows access to these repositories through an alternate set of user-centric REST URLs beginning with:

http://example.com/rest/api/1.0/users/~{userSlug}/repos
E.g. to list the forks of the repository with slug "nodejs" in the personal project of user with slug "johnsmith" using the regular REST URL you would make a GET to:
http://example.com/rest/api/1.0/projects/~johnsmith/repos/nodejs/forks
Using the alternate URL, you would make a GET to:
http://example.com/rest/api/1.0/users/johnsmith/repos/nodejs/forks

Index

This is an API for integrations to post and retrieve results from code analysis. This happens in the form of a 'report' which contains summary data about the analysis, and 'annotations' which are specific messages attached to lines in the code. Pull requests will display reports that have been created on the latest commit of the source branch and will show any annotations for these reports that are on lines that have been changed in the pull request.

Resources

/rest/insights/1.0/projects/{projectKey}/repos/{repositorySlug}/commits/{commitId}/reports/{key}/annotations/{externalId}

resource-wide template parameters
parametervaluedescription

projectKey

string

The project key

externalId

string

The external ID of the annotation that is to be updated or created

commitId

string

The commit ID on which the annotation belongs. This must be a full 40 character commit hash

key

string

The key of the report to which this annotation belongs

repositorySlug

string

The repository slug

Methods

PUT

Create an annotation with the given external ID, or replace it if it already exists. A request to replace an existing annotation will be rejected if the authenticated user was not the creator of the specified report.

Example request representations:

  • application/json [expand]

    Example
    {"line":2,"message":"This is a vulnerability, but I don't need to access it again so I haven't given it an external ID","path":"path/to/another/file/in/repo","severity":"HIGH"}

Example response representations:

  • 204 [expand]

    No content, indicating that the request succeeded.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user is not the author of the report, or the author no longer has sufficient permissions (REPO_READ).

  • 404 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The specified project, repository, commit, report or annotation does not exist.

/rest/insights/1.0/projects/{projectKey}/repos/{repositorySlug}/commits/{commitId}/reports/{key}/annotations

resource-wide template parameters
parametervaluedescription

projectKey

string

the project key

commitId

string

the commit ID on which the report is recorded. This must be a full 40 character commit tash

key

string

the report key

repositorySlug

string

the repository slug

Methods

DELETE

/rest/insights/1.0/projects/{projectKey}/repos/{repositorySlug}/commits/{commitId}/reports/{key}/annotations?externalId

Delete annotations for a given report that match the given external IDs, or all annotations if no external IDs are provided.

request query parameters
parametervaluedescription

externalId

string

the external IDs for the annotations that are to be deleted. Can be specified more than once to delete by more than one external ID, or can be unspecified to delete all annotations

Example response representations:

  • 204 [expand]

    The annotations were successfully deleted.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user has insufficient permissions to delete insight reports or was not the author (REPO_READ for author otherwise REPO_ADMIN).

  • 404 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The specified project, repository, commit or report does not exist.

POST

Add annotations to the given report. The request should be a JSON object mapping the string "annotations" to an array of maps containing the annotation data, as described below. See also the example request.
A few things to note:

  • Annotations are an extension of a report, so a report must first exist in order to post annotations. Annotations are posted separately from the report, and can be posted in bulk using this endpoint.
  • Only the annotations that are on lines changed in the unified diff will be displayed. This means it is likely not all annotations posted will be displayed on the pull request It also means that if the user is viewing a side-by-side diff, commit diff or iterative review diff they will not be able to view the annotations.
  • A report cannot have more than 1000 annotations by default, however this property is congurable at an instance level. If the request would result in more than the maximum number of annotations being stored then the entire request is rejected and no new annotations are stored.
  • There is no de-duplication of annotations on Bitbucket so be sure that reruns of builds will first delete the report and annotations before creating them.

Annotation parameters

Parameter Description Required? Restrictions Type
path The path of the file on which this annotation should be placed. This is the path of the file relative to the git repository. If no path is provided, then it will appear in the overview modal on all pull requests where the tip of the branch is the given commit, regardless of which files were modified. No String
line The line number that the annotation should belong to. If no line number is provided, then it will default to 0 and in a pull request it will appear at the top of the file specified by the path field. No Non-negative integer Integer
message The message to display to users Yes The maximum length accepted is 2000 characters, however the user interface may truncate this value for display purposes. We recommend that the message is short and succinct, with further details available to the user if needed on the page linked to by the the annotation link. String
severity The severity of the annotation Yes One of: LOW, MEDIUM, HIGH String
link An http or https URL representing the location of the annotation in the external tool No String
type The type of annotation posted No One of: VULNERABILITY, CODE_SMELL, BUG String
externalId If the caller requires a link to get or modify this annotation, then an ID must be provided. It is not used or required by Bitbucket, but only by the annotation creator for updating or deleting this specific annotation. No A string value shorter than 450 characters String

Example request representations:

  • application/json [expand]

    Example
    {"annotations":[{"externalId":"message-1","line":4,"link":"https://link.to.tool/that/produced/annotation/message-1","message":"This is a bug here because reasons","path":"path/to/file/in/repo","severity":"MEDIUM","type":"CODE_SMELL"},{"line":2,"message":"This is a vulnerability, but I don't need to access it again so I haven't given it an external ID","path":"path/to/another/file/in/repo","severity":"HIGH"},{"externalId":"file-annotation-1","line":0,"link":"https://link.to.tool/that/produced/annotation/file-annotation-1","message":"This whole file needs to be annotated","path":"path/to/file/in/repo","severity":"LOW","type":"VULNERABILITY"}]}

Example response representations:

  • 204 [expand]

    An empty response indicating that the request succeeded.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user is not the author of the report, or the author no longer has sufficient permissions (REPO_READ).

  • 404 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The specified project, repository, commit, or report does not exist.

GET

Retrieve the specified report's annotations.

Example response representations:

  • 200 - application/json (AnnotationsResponse) [expand]

    Example
    {"annotations":[{"reportKey":"report.key","externalId":"external.id","line":5,"link":"http://example.com/my/file/analysis?line=5","message":"This is an annotation message","path":"src/some/structure/file.ext","severity":"HIGH","type":"BUG"}]}

    The specified annotations.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user has insufficient permissions (REPO_READ needed) to get insight reports.

  • 404 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The specified project, repository, commit, or report does not exist.

/rest/insights/1.0/projects/{projectKey}/repos/{repositorySlug}/commits/{commitId}/reports

resource-wide template parameters
parametervaluedescription

projectKey

string

the project key

commitId

string

the commit ID on which the report is recorded. This must be a full 40 character commit hash

repositorySlug

string

the repository slug

Methods

GET

Retrieve all reports for the given commit.

Example response representations:

  • 200 - application/json (InsightReport) [expand]

    Example
    {"size":1,"limit":25,"isLastPage":true,"values":[{"data":[{"title":"data.title","value":9,"type":"NUMBER"}],"createdDate":12345,"details":"This is the details of the report, it can be a longer string describing the report","key":"report.key","link":"http://integration.host.com","logoUrl":"http://integration.host.com/logo","result":"PASS","title":"report.title","reporter":"Reporter/tool that produced this report"}],"start":0}

    a page of reports.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user has insufficient permissions (REPO_READ) to get insight reports.

  • 404 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The specified project, repository or commit does not exist.

/rest/insights/1.0/projects/{projectKey}/repos/{repositorySlug}/commits/{commitId}/reports/{key}

resource-wide template parameters
parametervaluedescription

projectKey

string

The project key

commitId

string

The commit ID on which the report is recorded. This must be a full 40 character commit hash

key

string

A unique string representing the report as chosen by the reporter. This should be unique enough to not clash with other report's keys. To do this, we recommend namespacing the key using reverse DNS

repositorySlug

string

The repository slug

Methods

GET

Retrieve the specified report.

Example response representations:

  • 200 - application/json (InsightReport) [expand]

    Example
    {"data":[{"title":"data.title","value":9,"type":"NUMBER"}],"createdDate":12345,"details":"This is the details of the report, it can be a longer string describing the report","key":"report.key","link":"http://integration.host.com","logoUrl":"http://integration.host.com/logo","result":"PASS","title":"report.title","reporter":"Reporter/tool that produced this report"}

    The specified report.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user has insufficient permissions (REPO_READ needed) to get insight reports.

  • 404 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The specified project, repository, commit, or report does not exist.

DELETE

Delete a report for the given commit. Also deletes any annotations associated with this report.

Example response representations:

  • 204 [expand]

    The report and associated annotations were successfully deleted.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user has insufficient permissions to delete insight reports or was not the author (REPO_READ for author otherwise REPO_ADMIN).

  • 404 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The specified project, repository, commit or report does not exist.

PUT

Create a new insight report, or replace the existing one if a report already exists for the given repository, commit, and report key. A request to replace an existing report will be rejected if the authenticated user was not the creator of the specified report.

The report key should be a unique string chosen by the reporter and should be unique enough not to potentially clash with report keys from other reporters. We recommend using reverse DNS namespacing or a similar standard to ensure that collision is avoided.

Report parameters

Parameter Description Required? Restrictions Type
title A short string representing the name of the report Yes Max length: 450 characters (but we recommend that it is shorter so that the display is nicer) String
details A string to describe the purpose of the report. This string may contain escaped newlines and if it does it will display the content accordingly. No Max length: 2000 characters String
result Indicates whether the report is in a passed or failed state No One of: PASS, FAIL String
data An array of data fields (described below) to display information on the report No Maximum 6 data fields Array
reporter A string to describe the tool or company who created the report No Max length: 450 characters String
link A URL linking to the results of the report in an external tool. No Must be a valid http or https URL String
logoUrl A URL to the report logo. If none is provided, the default insights logo will be used. No Must be a valid http or https URL String

Data parameters

The data field on the report is an array with at most 6 data fields (JSON maps) containing information that is to be displayed on the report (see the request example).

Parameter Description Type
title A string describing what this data field represents String
type The type of data contained in the value field. If not provided, then the value will be detected as a boolean, number or string. One of: BOOLEAN, DATE, DURATION, LINK, NUMBER, PERCENTAGE, TEXT String
value A value based on the type provided. Either a raw value (string, number or boolean) or a map. See below.
Type Field Value Field Type Value Field Display
None/Omitted Number, String or Boolean (not an array or object) Plain text
BOOLEAN Boolean The value will be read as a JSON boolean and displayed as 'Yes' or 'No'.
DATE Number The value will be read as a JSON number in the form of a Unix timestamp (milliseconds) and will be displayed as a relative date if the date is less than one week ago, otherwise it will be displayed as an absolute date.
DURATION Number The value will be read as a JSON number in milliseconds and will be displayed in a human readable duration format.
LINK Object: {"linktext": "Link text here", "href": "https://link.to.annotation/in/external/tool"} The value will be read as a JSON object containing the fields "linktext" and "href" and will be displayed as a clickable link on the report.
NUMBER Number The value will be read as a JSON number and large numbers will be displayed in a human readable format (e.g. 14.3k).
PERCENTAGE Number (between 0 and 100) The value will be read as a JSON number between 0 and 100 and will be displayed with a percentage sign.
TEXT String The value will be read as a JSON string and will be displayed as-is

Example request representations:

  • application/json [expand]

    Example
    {"data":[{"title":"Some title","value":"Some value","type":"TEXT"},{"title":"Build length","value":60000,"type":"DURATION"},{"title":"Download link","value":{"linktext":"installer.zip","href":"https://link.to.download/file.zip"},"type":"LINK"},{"title":"Build started date","value":1539656375,"type":"DATE"},{"title":"Code coverage","value":85,"type":"PERCENTAGE"},{"title":"Some count","value":5,"type":"NUMBER"}],"details":"This is the details of the report, it can be a longer string describing the report","title":"report.title","reporter":"Reporter/tool that produced this report","createdDate":1609808547688,"link":"http://insight.host.com","logoUrl":"http://insight.host.com/logo","result":"PASS"}

Example response representations:

  • 200 - application/json (insightReport) [expand]

    Example
    {"data":[{"title":"data.title","value":9,"type":"NUMBER"}],"createdDate":12345,"details":"This is the details of the report, it can be a longer string describing the report","key":"report.key","link":"http://integration.host.com","logoUrl":"http://integration.host.com/logo","result":"PASS","title":"report.title","reporter":"Reporter/tool that produced this report"}

    the created report.

  • 400 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    One of the following error cases occurred (check the error message for more details):

    • The request does not contain a report title.
    • The data field contains unsupported objects.
    • The request does not contain a report key/
    • The provided commit hash is invalid, according to the validation rules mentioned for the commitId above.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user is not permitted to create an insight report or authentication failed.

/rest/insights/1.0/projects/{projectKey}/repos/{repositorySlug}/commits/{commitId}/annotations

resource-wide template parameters
parametervaluedescription

projectKey

string

the project key

commitId

string

the commit ID on which the report is recorded. This must be a full 40 character commit tash

repositorySlug

string

the repository slug

Methods

GET

/rest/insights/1.0/projects/{projectKey}/repos/{repositorySlug}/commits/{commitId}/annotations?externalId&key&path&severity&type

Retrieve the specified report's annotations.

request query parameters
parametervaluedescription

externalId

string

key

string

the report key

path

string

severity

string

type

string

Example response representations:

  • 200 - application/json (AnnotationsResponse) [expand]

    Example
    {"annotations":[{"reportKey":"report.key","externalId":"external.id","line":5,"link":"http://example.com/my/file/analysis?line=5","message":"This is an annotation message","path":"src/some/structure/file.ext","severity":"HIGH","type":"BUG"}]}

    The specified annotations.

  • 401 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The currently authenticated user has insufficient permissions (REPO_READ needed) to get insight reports.

  • 404 - application/json (errors) [expand]

    Example
    {"errors":[{"context":null,"message":"A detailed error message.","exceptionName":null}]}

    The specified project, repository, commit, or report does not exist.