Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically access the full snippet in Gitlab?

Question

My end goal is to have an offline, updateable copy of my snippets (including title & description) such that I can search and use them easily. How can I get all my snippets from Gitlab to my local machine? I'm using Gitlab version is 13.12.10-ee.

What I've looked into

Cloning snippets

It's possible to clone snippet contents in Gitlab, but this only includes the file associated with the snippet. The title and description are excluded.

E.g. when I do git clone [email protected]:snippets/$snippet_id.git I only receive the files associated with the snippet, not the title and the description:

enter image description here

I've checked the documentation but could not find any mention of interacting with the description through git.

Gitlab API

I found that the Gitlab API has a snippets endpoint. However, when I use the python-gitlab CLI tool and request a single snippet with gitlab snippet get --id 123 I only get the ID and the title.
When I do gitlab snippet content --id 123 I only get the contents of the file associated with the snippet.

like image 509
Saaru Lindestøkke Avatar asked Mar 06 '26 16:03

Saaru Lindestøkke


1 Answers

From a Unix shell, using CuRL and jq:

GITLAB_API_TOKEN=<your_api-scoped_token>
SNIPPET_ID=<snippet_id_number>

# Parse the JSON for the fields you want (.title,.description)
curl --header "PRIVATE-TOKEN: $GITLAB_API_TOKEN" \
  "https://gitlab.example.com/api/v4/snippets/$SNIPPET_ID" \
  | jq '.title,.description'

# Use the /raw endpoint to get the full snippet content
curl --header "PRIVATE-TOKEN: $GITLAB_API_TOKEN" \
  "https://gitlab.example.com/api/v4/snippets/$SNIPPET_ID/raw

Using python-gitlab:

import gitlab
GITLAB_API_TOKEN=<your_api-scoped_token>
SNIPPET_ID=<snippet_id_number>

gl = gitlab.Gitlab('https://gitlab.example.com', private_token=GITLAB_API_TOKEN)
snippet = gl.snippets.get(SNIPPET_ID)
title = snippet.title
descr = snippet.description
cont  = snippet.content()
like image 58
mike Avatar answered Mar 08 '26 19:03

mike