Problems Updating File in Repo via API

I have a gitea server set up with docker and a webserver that uses the gitea swagger API to push and update files on the gitea server. Now when I send an http request to upload a file into a repository via the API this works completely fine. The authorization token is inside the header and the content of the file is in the body of the request and the file gets pushed just fine.

However when I use the command to update the file I need to provide the SHA hash for the file as it is currently before being changed. I created a file for testing purposes (A simple .txt filled with a single sentence) and uploaded it. I then cloned the repo, used the unix command “sha1sum” to get to the SHA value of the file as it is before editing and then provided this SHA to update the file with a different content. However I get rejected with a 422 Unprocessable Entitiy response and I can not explain why that is. The formatting should be correct. Does the SHA hashmean something differently or is there another, proper way to generate the SHA hash?

This is how the http request is currently being put together. I am using the python library requests for this. Again for upload this works without a hitch.

Upload file:

// Header including authorization token
headers = {'Access-Control-Allow-Origin': 'GITEA SERVER URL', 'accept' : 'application/json', Authorization' : 'token TOKEN VALUE'}
// Body containing file contents encoded in base 64
data={"content": base64.b64encode(fileString)}
// Send Request to Upload the file'GITEA SERVER URL/api/v1/repos/owner/repo/contents/filepath', data=data, headers=headers)

Update file:

// Header including authorization token
headers = {'Access-Control-Allow-Origin': 'GITEA SERVER URL', 'accept' : 'application/json', 'Authorization' : 'token TOKEN VALUE'}
// Body containing file contents encoded in base 64, as well as old SHA value
data={"content": base64.b64encode(fileString), "sha":"SHA VALUE"} 
response=requests.put('GITEA SERVER URL/api/v1/repos/owner/repo/contents/filepath', data=data, headers=headers) 

I would be very thankful for any help on this matter. :slight_smile:

To provide a bit more context, this is how the response body looks:

{"message":"sha does not match [given: 3374860ef7271d17384109b2b99e466a848aeec2, expected: 6a9a28ed738ac2d028fce337a0a11b36da9bceff]","url":"http://gitea:3000/api/swagger"}

As you can see my generated hash seems to be wrong. When I use the correct sha provided in the response it works, but I am still unsure how this hash value is generated.

1 Like

I don’t have the java command, but to find the right SHA, you could play the following git command

In my case, the following command
$ git cat-file -p master^{tree}

Provide the output and the sha is the same than expected in the message “sha does not match …”

100644 blob ff74ef0650964cf5f8ae8b9daa1c31f207a4c384 test.txt