Creating project API tokens programmatically#
For example, if you're setting up coverage for all your repositories and prefer not to use a single account API token that grants the same permissions as an administrator, you need to create an individual project API token for each repository.
Example: Creating project API tokens for all repositories in an organization#
This example creates new project API tokens for all the repositories in an organization and outputs a comma-separated list of repository names and corresponding token strings.
The example script:
- Defines the account API token used to authenticate on the Codacy API, the Git provider, and the organization name.
- Calls the Codacy API endpoint listOrganizationRepositories to retrieve the list of repositories in the organization.
- Uses jq to select only the name of the repositories.
- Asks for confirmation from the user before making any changes.
- For each repository, calls the Codacy API endpoint createRepositoryApiToken to create a new project API token and uses jq to obtain only the created token string.
- Outputs a comma-separated list of the repository names and the corresponding new token strings.
- Pauses a few seconds between requests to the Codacy API to avoid rate limiting.
#!/bin/bash CODACY_API_TOKEN="<your account API token>" GIT_PROVIDER="<your Git provider>" # gh, ghe, gl, gle, bb, or bbe ORGANIZATION="<your organization name>" repositories=$(curl -sX GET "https://app.codacy.com/api/v3/organizations/$GIT_PROVIDER/$ORGANIZATION/repositories" \ -H "api-token: $CODACY_API_TOKEN" \ | jq -r ".data | .name") count=$(echo "$repositories" | wc -l) read -p "Create project tokens for $count repositories? (y/n) " choice if [ "$choice" = "y" ]; then echo "$repositories" | while read repository; do echo -n "$repository," curl -sX POST "https://app.codacy.com/api/v3/organizations/$GIT_PROVIDER/$ORGANIZATION/repositories/$repository/tokens" \ -H "api-token: $CODACY_API_TOKEN" \ | jq -r ".data | .token" sleep 2 # Wait 2 seconds done else echo "No changes made."; fi
chart,<new project API token> docs,<new project API token> website,<new project API token> [...]
For the sake of simplicity, the example doesn't consider paginated results obtained from the Codacy API. Learn how to use pagination to ensure that you process all results returned by the API.
Share your feedback 📢
Did this page help you?
Thanks for the feedback! Is there anything else you'd like to tell us about this page?
255 characters left
We're sorry to hear that. Please let us know what we can improve:
255 characters left
Alternatively, you can create a more detailed issue on our GitHub repository.
Thanks for helping improve the Codacy documentation.
Edit this page on GitHub if you notice something wrong or missing.
If you have a question or need help please contact email@example.com.