Getting started overview
To begin interacting with the Bitbucket API, developers typically follow a sequence of steps that involve setting up an Atlassian account, configuring API access, and making an authenticated request. The Bitbucket API primarily uses a RESTful architecture, allowing for standard HTTP methods (GET, POST, PUT, DELETE) to manage resources such as repositories, pull requests, and users within Bitbucket Cloud. Authentication methods include OAuth 2.0 for third-party applications and app passwords for scripting or personal integrations. Understanding these fundamental components is key to a smooth integration process.
This guide provides a structured approach to initiate your development efforts with Bitbucket API, covering account creation, credential generation, and the execution of your first API call. It aims to streamline the initial setup phase, enabling you to quickly move towards building more complex integrations or automations.
Here's a quick reference table outlining the essential steps:
| Step | What to Do | Where |
|---|---|---|
| 1. Create Account | Sign up for a Bitbucket Cloud account. | Bitbucket Homepage |
| 2. Choose Auth Method | Decide between OAuth 2.0 (for apps) or App Passwords (for scripts). | Bitbucket API authentication methods |
| 3. Generate Credentials | Create an app password or register an OAuth consumer. | Bitbucket Account Settings or Workspace Settings |
| 4. Make Request | Send an authenticated HTTP request to a Bitbucket API endpoint. | Using a tool like curl or a programming language's HTTP client |
Create an account and get keys
Before making any API calls, you need an active Bitbucket Cloud account. Bitbucket offers a free plan for up to 5 users, which is sufficient for initial development and testing. If you already have an Atlassian account (e.g., for Jira or Confluence), you can use those credentials to access Bitbucket.
1. Sign up for a Bitbucket Cloud account
Navigate to the Bitbucket sign-up page and follow the prompts to create a new account. You'll need to provide an email address and create a password. Once registered, you'll have access to your Bitbucket workspace where you can create repositories and manage team members.
2. Choose an authentication method
The Bitbucket API supports two primary authentication methods:
- OAuth 2.0: This is the recommended method for third-party applications that need to access Bitbucket resources on behalf of users. It provides a secure way to grant limited access without sharing user credentials directly. For a deeper understanding of OAuth 2.0 flows, consult the OAuth 2.0 specification.
- App Passwords: These are specific passwords generated for programmatic access, often used for scripts, CI/CD pipelines, or personal integrations where OAuth 2.0 might be overkill. App passwords grant access to your account with specific permissions. They are a form of basic authentication, where the username is your Atlassian account ID and the password is the generated app password.
For getting started quickly, especially for personal scripts or testing, app passwords are generally simpler to set up. For robust applications, OAuth 2.0 offers greater security and flexibility.
3. Generate API credentials (App Password)
To generate an app password:
- Log in to your Bitbucket account.
- Click on your avatar in the bottom left corner and select Personal settings.
- In the left sidebar, under Security, click App passwords.
- Click the Create app password button.
- Give your app password a descriptive label (e.g., "My First API Test").
- Select the necessary permissions (scopes) for your integration. For a first test, granting "Read" access to repositories and "Account" might be sufficient. Be judicious with permissions, only granting what is absolutely required.
- Click Create.
- Bitbucket will display the app password. Copy this password immediately, as it will not be shown again. This password will be used in place of your regular account password for API requests.
For detailed steps on creating app passwords, refer to the Bitbucket API authentication guide.
Your first request
Once you have your app password, you can make your first authenticated request to the Bitbucket API. A common starting point is to fetch a list of repositories associated with your account or workspace.
Endpoint for listing repositories
The endpoint to list repositories for a workspace is typically https://api.bitbucket.org/2.0/repositories/{workspace}, where {workspace} is the unique identifier for your Bitbucket workspace. You can find your workspace ID by navigating to your Bitbucket dashboard; it's usually part of the URL (e.g., bitbucket.org/{workspace_id}/).
Example using curl
Using curl is a straightforward way to test API endpoints from your terminal. Replace {your_username} with your Atlassian account ID (usually your email address), {your_app_password} with the app password you generated, and {your_workspace_id} with your actual workspace identifier.
curl -u "{your_username}:{your_app_password}" \
https://api.bitbucket.org/2.0/repositories/{your_workspace_id}
A successful response will return a JSON object containing a list of your repositories, similar to this (truncated for brevity):
{
"pagelen": 10,
"values": [
{
"scm": "git",
"website": null,
"has_wiki": false,
"uuid": "{repository_uuid}",
"links": {
"self": {
"href": "https://api.bitbucket.org/2.0/repositories/{your_workspace_id}/my-repo/"
},
"html": {
"href": "https://bitbucket.org/{your_workspace_id}/my-repo/"
}
},
"fork_policy": "allow_forks",
"name": "my-repo",
"project": {
"key": "PROJ",
"uuid": "{project_uuid}",
"name": "My Project",
"links": {
"self": {
"href": "https://api.bitbucket.org/2.0/workspaces/{your_workspace_id}/projects/PROJ"
},
"html": {
"href": "https://bitbucket.org/{your_workspace_id}/workspace/projects/PROJ"
}
}
},
"slug": "my-repo",
"is_private": true,
"description": "A sample repository.",
"has_issues": false,
"owner": {
"display_name": "Your Name",
"uuid": "{owner_uuid}",
"links": {
"self": {
"href": "https://api.bitbucket.org/2.0/users/{owner_uuid}"
},
"html": {
"href": "https://bitbucket.org/{your_username}/"
},
"avatar": {
"href": "https://avatar-management--avatars.us-west-2.prod.public.atl-paas.net/initials/{initials}/128.png"
}
}
},
"created_on": "2023-01-01T12:00:00.000000+00:00",
"size": 12345,
"language": "python",
"has_pullrequests": true,
"updated_on": "2023-01-01T13:00:00.000000+00:00"
}
],
"page": 1,
"size": 1
}
Example using Python requests library
For programmatic access, a language like Python with the requests library is a common choice. Ensure you have requests installed (pip install requests).
import requests
import os
# Replace with your actual username and app password
USERNAME = os.environ.get("BITBUCKET_USERNAME")
APP_PASSWORD = os.environ.get("BITBUCKET_APP_PASSWORD")
WORKSPACE_ID = os.environ.get("BITBUCKET_WORKSPACE_ID")
if not all([USERNAME, APP_PASSWORD, WORKSPACE_ID]):
print("Please set BITBUCKET_USERNAME, BITBUCKET_APP_PASSWORD, and BITBUCKET_WORKSPACE_ID environment variables.")
exit()
url = f"https://api.bitbucket.org/2.0/repositories/{WORKSPACE_ID}"
try:
response = requests.get(url, auth=(USERNAME, APP_PASSWORD))
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
repositories = response.json()
print("Successfully fetched repositories:")
for repo in repositories.get("values", []):
print(f"- {repo['name']} (Private: {repo['is_private']})")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
if response.status_code == 401:
print("Authentication failed. Check your username and app password.")
elif response.status_code == 403:
print("Permission denied. Check the app password's scopes.")
else:
print(f"Response status code: {response.status_code}")
print(f"Response body: {response.text}")
This Python script fetches the list of repositories and prints their names and privacy status. It also includes basic error handling for common issues like authentication failures.
Common next steps
After successfully making your first API call, consider these common next steps to deepen your integration with Bitbucket:
- Explore other API endpoints: The Bitbucket API offers a wide range of endpoints for managing pull requests, branches, commits, users, and more. Consult the comprehensive Bitbucket Cloud REST API documentation to discover additional functionalities.
- Implement OAuth 2.0: If you're building a public or multi-user application, transitioning to OAuth 2.0 is crucial for secure and scalable authentication. This involves registering an OAuth consumer in your Bitbucket workspace settings and implementing the OAuth authorization flow. The Bitbucket OAuth 2.0 documentation provides detailed instructions.
- Webhooks: Set up webhooks to receive real-time notifications about events in your Bitbucket repositories, such as push events, pull request updates, or issue comments. Webhooks are essential for building reactive applications that respond to changes in Bitbucket. For guidance on securing webhooks, consider best practices like those outlined in Twilio's webhook security guide.
- Integrate with Atlassian products: Bitbucket is part of the Atlassian ecosystem. Explore integrations with Jira for issue tracking, Confluence for documentation, and Opsgenie for incident management. The Atlassian Developer platform provides resources for building Connect apps that seamlessly integrate across these products.
- Use an SDK: While Bitbucket does not officially provide SDKs for all languages, community-maintained libraries might exist for popular programming environments, simplifying API interactions by abstracting HTTP requests and JSON parsing.
- Error handling and rate limits: Implement robust error handling in your application to gracefully manage API errors. Be aware of Bitbucket's API rate limits to avoid being temporarily blocked. The API documentation provides information on Bitbucket API rate limiting and how to handle
429 Too Many Requestsresponses.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting tips:
- 401 Unauthorized: This typically means your authentication credentials (username or app password) are incorrect. Double-check for typos. Remember that the username for app passwords is your Atlassian account ID (often your email) and not necessarily your Bitbucket display name. Regenerate the app password if you suspect it was copied incorrectly or has expired.
- 403 Forbidden: A 403 error indicates that your app password does not have the necessary permissions (scopes) to access the requested resource. Go back to your app password settings in Bitbucket and ensure you have granted the appropriate "Read" or "Write" permissions for the resources you are trying to access (e.g., "Repositories" > "Read").
- 404 Not Found: This error often means the endpoint URL is incorrect or the resource you are trying to access does not exist. Verify the workspace ID and repository slug in your URL. Ensure your workspace ID is correct and that the repository exists within that workspace and is accessible to your user.
- Incorrect Workspace ID: Your workspace ID is distinct from your display name. It's the string that appears in the URL after
bitbucket.org/when you navigate to your Bitbucket dashboard or a repository (e.g.,bitbucket.org/your-workspace-id/your-repo). - JSON parsing errors: If you're receiving a response but your code can't parse it, ensure the response is indeed JSON. Sometimes, an API error might return HTML or plain text instead of JSON. Inspect the
Content-Typeheader of the response. - Network issues: Confirm your internet connection is stable and there are no firewall rules blocking outgoing requests to
api.bitbucket.org. - Refer to official documentation: The Bitbucket Cloud REST API documentation is the authoritative source for endpoint details, request formats, and error codes. Review the specific endpoint you are trying to call for any particular requirements.