How To Read and Save a File Using Gitlab API

This tutorial help to save a file using GitLab v4 API. I have already shared a tutorial that helps to read a file from gitlab repository.

We’ll save that file GitLab repo using GitLab API. Sometimes, We need to read a file from GitLab repo, and modify and save it into GitLab repo.

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

Update Existing File in the Repository

This allows you to update a single file. For updating multiple files with a single request, This is a protected api.

The Syntax:

PUT /projects/:id/repository/files/:file_path

Update a file Using Gitlab V4 API

I am using laravel 8 to create an API and expose an endpoint to update a file into Gitlab.

Let’s create a TestController.php file into Http/Controller folder.

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

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;
 }

Let’s create an endpoint that ll use to update file from gitlab.

Route::post('save_gitlab_file_content', 'TestController@saveGitlabFileContent');

Create above method into the controller file:

public function saveGitlabFileContent(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->updateFileInRepo($parameters['project_id'], $parameters['file_path'], $parameters['payloads']);
   return $this->jsonpSuccess($resp);  
}

Let’s define the service method to connect with gitlab api and save the file.

public function updateFileInRepo($project_id, $filename, $payload) {
      $client = $this->_client($this->gitlabAPI); 
      $response = $client->put("projects/$project_id/repository/files/$filename", ['json' => $payload])->getBody()->getContents();   
      
      return json_decode($response); 
}