How To Read File From Gitlab Using API

Parvez Alam
2 min readAug 4, 2022

This tutorial help to read a file from GitLab using API. I am creating a rest API that reads data from GitLab project and returns it in text format data.

Sometimes, we need to read a file from the GitLab repo and modify it, I’ll share a separate tutorial to save a file into GitLab repo using API.

Repository files API helps to fetch, create, update, and delete files from your repository.

Get the file from a repository

The get file API help to receive information about a file in the repository like name, size, and content. File content is Base64 encoded.

This endpoint can be accessed without authentication if the repository is publicly accessible.

The Syntax: GET /projects/:id/repository/files/:file_path

Read a file from Gitlab Using V4 API

I am using laravel 8 to create an API and expose an endpoint to read files from Gitlab. Let’s create a TestController.php file in Http/Controller folder.

private function _client() { $token = env('GITLAB_TOKEN'); $client = new Client([ 'base_uri' => env("GITLAB_URL"), 'timeout' => 300, 'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json", "PRIVATE-TOKEN" => $token], 'http_errors' => false, 'verify' => false ]); return $client; }

First, we’ll create a connect method that’ll connect laravel application with GitLab v4 API.

Let’s create an endpoint that ll use to read files from GitLab.

Route::post('read_gitlab_file_content', '[email protected]');

Create the above method into the controller file:

public function getGitlabFileContent(request $request) { $parameters = $request->json()->all(); if(empty($parameters['project_id'])) { return $this->jsonpError('project id is empty', 400, 400); } if(empty($parameters['file_path'])) { return $this->jsonpError('file_path is empty', 400, 400); } $resp = $this->getFileInRepo($parameters['project_id'], $parameters['file_path']); return $this->jsonpSuccess($resp); }

Let’s define a service method to connect with gitlab API and read files.

public function getFileInRepo($project_id, $filename) { $client = $this->_client(); $response = $client->get("projects/$project_id/repository/files/$filename/raw")->getBody()->getContents(); return $response; }

Originally published at https://www.restapiexample.com on August 4, 2022.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/