rss resume / curriculum vitae linkedin linkedin gitlab github twitter mastodon instagram
Tip: Uploading files programmatically in Gitlab
Jan 02, 2017

The last piece in the Docker Full Development Workflow is uploading the file generated by templenv to the Merge Request that originated it. Let’s see how can we use the Gitlab API for doing all of all this.

Token

First thing required for this is to get the token to be used for all the requests, visiting the https://gitlab.domain/profile/account, let’s assume that this token is ABCDEFG

Getting project ID

Since the file will be uploaded to a project, and the note (comment) will be added to a Merge Request in that said project, we must get the project ID first:

curl -i -k -H "PRIVATE-TOKEN: ABCDEFG" \
  "https://gitlab.domain/api/v3/projects/namespace%2Frepo" -X GET

That should output a JSON including the project id, this ID will be used for the next API calls. Let’s assume, this id is 9999

Uploading the file

If we wanted to upload a file we will use something like this:

curl -i -k -H "PRIVATE-TOKEN: ABCDEFG" \
  "https://gitlab.domain/api/v3/projects/9999/uploads" -X POST -F 'file=@docker-compose.xml'

This should return a JSON including the markdown to be used in the next calls to add a comment to the merge request.

Getting the Merge Request ID

Let’s say we have a Merge Request 1234, in this project 9999, we will use the API to get the ID first like this:

curl -i -k -H "PRIVATE-TOKEN: ABCDEFG" \
  "https://gitlab.domain/api/v3/projects/9999/merge_requests?iid=1234" -X GET

This will return a JSON as well, let’s assume the ID for this merge request is 4567.

Create note in merge request

Finally we will need to create the note and add the linked file like this:

curl -i -k -H "PRIVATE-TOKEN: ABCDEFG" \
  "https://gitlab.domain/api/v3/projects/9999/merge_requests/4567/notes" \
  -X POST \
  -F 'body=Link to file [docker-compose.yml](/uploads/9125e38ea55c5415a294af6c463f9af5/docker-compose.yml)'

Back to posts