如何使用 Perl 在 Gitlab 中创建问题

How to create issues in Gitlab with Perl

我正在使用下面的代码在 Gitlab 上创建问题,但它不起作用:

use strict;
use warnings;
use Data::Dumper;
use LWP::UserAgent;
use JSON;
use Carp;

# establish the API base URI
my $api_base = 'https://gitlab.com/api/v3/projects/XXXXXXX/issues';

# Try the url with API v4:  https://gitlab.com/api/v4/projects/XXXXXXX/issues but it also didn't work

# personal access token
# https://docs.gitlab.com/ee/api/README.html#personal-access-tokens
# https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html

my $access_token = 'XXXXXXXXXXXXXXXXX';

my $ua = LWP::UserAgent->new;

# $res is an HTTP::Response object
# see: https://metacpan.org/pod/HTTP::Response
my $res = $ua->get( $api_base, 
'Private-Token' => $access_token,
'title' => 'Teste',
'description' =>'Description'
) or croak "unable to complete the HTTP request";

my $o = decode_json( $res->decoded_content );

print Dumper $o;

我的代码有什么问题?

这可能有几个问题。首先,如果您的设置有问题,get 不会 return false,因此请检查 $res 实际持有的内容。它可能是关于您的 HTTPS 请求的 SSL 的信息。

根据 API documentation,您似乎应该对 API v4 做一个 POST。您需要创建一个请求,将您的令牌作为 header,并将您的问题作为 JSON 编码格式的 body。

#!/usr/bin/env perl

use warnings;
use strict;

use Carp;
use Data::Dumper;
use JSON;
use LWP::UserAgent;

# To get the project ID you must query for your projects
# this can be found with a HTTP GET to
# https://gitlab.com/api/v4/users/<USERNAME>/projects
my $api_base     = 'https://gitlab.com/api/v4/projects/<PROJECT ID>/issues';
my $access_token = 'xxx';

my $ua           = LWP::UserAgent->new;
my $request_body = encode_json(
    {
        title       => 'Some tite',
        description => 'See all available parameters in the API doc linked above',
    }
);

my $request = HTTP::Request->new( 'POST', $api_base );
$request->header( 'Content-Type'  => 'application/json' );
$request->header( 'PRIVATE-TOKEN' => $access_token );
$request->content( $request_body );

my $response         = $ua->request( $request );
my $decoded_response = decode_json( $response->decoded_content );

print Dumper $decoded_response;