Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Update an existing snippet via API (Python)

Brendan DeBrincat
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
July 26, 2022

I'm trying to update the content of an existing snippet via the API (using Python requests). I've written plenty of other automation, but this endpoint is giving me trouble. Probably because I'm not doing multipart form-data part correctly.

import os
import requests
import json

# Authenticate
token_response = requests.post(
url="https://bitbucket.org/site/oauth2/access_token",
auth=(f"{BITBUCKET_KEY}", f"{BITBUCKET_SECRET}"),
data={"grant_type":"client_credentials"}
).json()
access_token = token_response['access_token']

# Update
url = f"https://api.bitbucket.org/2.0/snippets/{workspace}/{encode_id}"
headers = {
"Accept": "application/json",
"Content-Type": "multipart/form-data",
"Authorization": f"Bearer {access_token}"
}
files = {'my-file.md': open('my-file.md','rb')}
response = requests.request(
"PUT",
url,
headers=headers,
files=files
)
if response.status_code != 200:
print(f"Got HTTP {response.status_code} on snippet write: {response.text}")
exit(2)

And the API is returning `Bad Request (400)` without any further context. Any ideas what I'm doing wrong? :) 

1 answer

0 votes
Mark C
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
September 14, 2022

Hi @Brendan DeBrincat,

Thank you for reaching out to the community.

Would it be possible for you to try to use the below content-type instead?

application/json; charset='utf-8'

Based on our API 2.0 documentation here, here's how you can update a snippet's file contents and title using CURL command:

curl -X PUT -H "application/json; charset='utf-8'" -H "Authorization: Bearer <access_token>" https://api.bitbucket.org/2.0/snippets/workspace_id/encoded_id -F title="test123" -F file=@TEST.md

You can also try the CURL command above to see if the API endpoint works.
Additionally, you can add "-vvv" flag to debug the CURL command.

Hope it helps and let me know if you have further questions.

Regards,
Mark C

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PERMISSIONS LEVEL
Product Admin
TAGS
AUG Leaders

Atlassian Community Events