Skip to content

Instantly share code, notes, and snippets.

@LcTrKiD
Created June 26, 2019 20:41
Show Gist options
  • Save LcTrKiD/dcdd6ad2bde9ff1fa15b0649e3e7c7c2 to your computer and use it in GitHub Desktop.
Save LcTrKiD/dcdd6ad2bde9ff1fa15b0649e3e7c7c2 to your computer and use it in GitHub Desktop.
Gitlab API (Create Branch and Add file)
import base64
import requests
class Gitlab(object):
def __init__(self, gl_url, gl_token):
self.url = gl_url
self.token = gl_token
def create_branch(self, project_id, branch, ref):
''' Create a branch in a project by its id '''
request = (f'{self.url}'
f'/api/v4/projects/{project_id}/repository/'
f'branches?branch={branch}&ref={ref}')
header = {'PRIVATE-TOKEN': self.token}
try:
request = requests.post(request,
headers=header)
response = request.json()
return response
except requests.exceptions.RequestException as e:
return f'Post request failed: {e}'
def add_file(self, project_id, file_path, branch, content, commit_message):
''' Create a file in a selected branch
with the content in base64 file_path: ex. lib/test.txt '''
if '/' in file_path:
file_path = file_path.replace('/', '%2F')
if '.' in file_path:
file_path = file_path.replace('.', '%2E')
with open(content.name, 'r') as content:
content = content.read()
content = base64.b64encode(content.encode('utf-8'))
content = content.decode('utf-8')
request = (f'{self.url}'
f'/api/v4/projects/{project_id}/repository/'
f'files/{file_path}')
header = {'PRIVATE-TOKEN': self.token,
'Content-Type': 'application/json'}
data = {'branch': branch, 'content': content,
'encoding': 'base64', 'commit_message': commit_message}
try:
request = requests.post(request,
headers=header,
json=data)
response = request.json()
return response
except requests.exceptions.RequestException as e:
return f'Post request failed: {e}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment