Commit 21c47855 authored by Roman Lacko's avatar Roman Lacko
Browse files

Update pod-GitLab-API.md

parent eb1151f1
Loading
Loading
Loading
Loading
+172 −122
Original line number Original line Diff line number Diff line
@@ -8,6 +8,7 @@ See [GitLab API](http://doc.gitlab.com/ce/api/) for details.


# SYNOPSIS
# SYNOPSIS


```{.pl}
use GitLab::API;
use GitLab::API;
use GitLab::Users;
use GitLab::Users;
use GitLab::Groups;
use GitLab::Groups;
@@ -22,113 +23,136 @@ See [GitLab API](http://doc.gitlab.com/ce/api/) for details.
die("Request failed: " . $response->message) unless $response->is_success;
die("Request failed: " . $response->message) unless $response->is_success;


# do something with users or groups
# do something with users or groups
```


# DESCRIPTION
# DESCRIPTION


- new()
- `new()`


    ```{.pl}
    $gitlab = GitLab::API->new(arg => value, ...);
    $gitlab = GitLab::API->new(arg => value, ...);
    ```


    Creates a new instance of [GitLab::API](https://metacpan.org/pod/GitLab::API). Takes a hash of arguments:
    Creates a new instance of `GitLab::API`. Takes a hash of arguments:


        Login       user login
    | argument      | description                                               |
        Email       user e-mail, required only if Login is not provided,
    | ------------- | --------------------------------------------------------- |
        Password    user password
    | Login       | user login                                                |
        AuthToken   authentication token
    | Email       | user e-mail, required only if Login is not provided,    |
        URL         url to connect to, usually https://gitlab.domain/api/v3
    | Password    | user password                                             |
        DieOnError  see die_on_error() method
    | AuthToken   | authentication token                                      |
    | URL         | url to connect to, usually `https://gitlab.domain/api/v3 |
    | DieOnError  | see `die_on_error()` method                               |


    `URL` is always required.
    `URL` is always required.
    The method also requires _either_ `AuthToken` _or_ ((`Login` or `Email`) and `Password`).
    The method also requires __either__ `AuthToken` __or__ ((`Login` or `Email`) and `Password`).
    That is, the only meaningful combinations are
    That is, the only meaningful combinations are


    ```{.pl}
    GitLab::API->new(URL => $URL, AuthToken  => $TOKEN);
    GitLab::API->new(URL => $URL, AuthToken  => $TOKEN);
    GitLab::API->new(URL => $URL, Login => $LOGIN, Password => $PASSWD);
    GitLab::API->new(URL => $URL, Login => $LOGIN, Password => $PASSWD);
    GitLab::API->new(URL => $URL, Email => $EMAIL, Password => $PASSWD);
    GitLab::API->new(URL => $URL, Email => $EMAIL, Password => $PASSWD);
    ```


- sudo()
- `sudo()`


    ```{.pl}
    $gitlab->sudo($username);
    $gitlab->sudo($username);
    $gitlab->sudo();
    $gitlab->sudo();
    ```


    Similar to [sudo(8)](https://metacpan.org/pod/sudo), changes identity to the user with the `$username`.
    Similar to [sudo(8)](https://linux.die.net/man/8/sudo), changes identity to the user with the `$username`.
    If the `$username` argument is not defined, changes the identity back to the original user.
    If the `$username` argument is not defined, changes the identity back to the original user.


    _This feature is available only to the admins._
    __This feature is available only to the admins.__
    You can test for that with the ["whoami"](#whoami) method this way:
    You can test for that with the [`whoami`](#whoami) method this way:


    ```{.pl}
    if ($gitlab->whoami()->{is_admin}) {
    if ($gitlab->whoami()->{is_admin}) {
        # Booyah!
        # Booyah!
    }
    }
    ```


- whoami()
- `whoami()`


    Returns the user whose authentication key is used for the request (or impersonated user if ["sudo"](#sudo) is in effect).
    Returns the user whose authentication key is used for the request (or impersonated user if [`sudo`](#sudo) is in effect).
    See ["REQUEST METHODS"](#request-methods) below.
    See ["REQUEST METHODS"](#request-methods) below.


- is\_admin()
- `is_admin()`


    ```{.pl}
    $gitlab->is_admin()
    $gitlab->is_admin()
    ```


    Returns true if the logged in user has administrator permissions.
    Returns `true` if the logged in user has administrator permissions.
    The result is not affected by ["sudo()"](#sudo).
    The result is not affected by [`sudo()`](#sudo).


- die\_on\_error()
- `die_on_error()`


    ```{.pl}
    my $value = $gitlab->die_on_error();
    my $value = $gitlab->die_on_error();
    $gitlab->die_on_error($value);
    $gitlab->die_on_error($value);
    ```


    When called without an argument, returns the current value of the settings.
    When called without an argument, returns the current value of the settings.
    Otherwise sets the first argument as the value.
    Otherwise sets the first argument as the value.


    If enabled, any call that returns an unsuccessful (!= 2\*\*) HTTP code will call `Carp/croak` with the status code.
    If enabled, any call that returns an unsuccessful (!= 2\*\*) HTTP code will call `Carp::croak` with the status code.
    If disabled, unsuccessful calls will simply return `undef`.
    If disabled, unsuccessful calls will simply return `undef`.


    The setting can be 'overriden' temporarily with the `-immortal => 1` option passed to the method.
    The setting can be 'overriden' temporarily with the `-immortal => 1` option passed to the method.
    See ["exec\_request"](#exec_request) below.
    See [`exec_request`](#exec_request) below.


## Internal Methods
## Internal Methods


The following methods are intended to be called from additional methods implemented by `GitLab::*` modules.
The following methods are intended to be called from additional methods implemented by `GitLab::*` modules.
**It is not recommended to use these methods directly.**
**It is not recommended to use these methods directly.**


- http()
- `http()`


    Returns the HTTP User Agent.
    Returns the HTTP User Agent.


- json()
- `json()`


    Returns the JSON decoder.
    Returns the JSON decoder.


- response()
- `response()`


    Returns the HTTP response of the last method.
    Returns the HTTP response of the last method.


- login()
- `login()`


    ```{.pl}
    $gitlab->login(arg => value, ...);
    $gitlab->login(arg => value, ...);
    ```


    With provided login information (`Email`, `Login`, `Password`), this method attempts to obtain user's private token.
    With provided login information (`Email`, `Login`, `Password`), this method attempts to obtain user's private token.
    Under the hood it simply calls the [session](http://docs.gitlab.com/ce/api/session.html) API method.
    Under the hood it simply calls the [session](http://docs.gitlab.com/ce/api/session.html) API method.


- create\_uri()
- `create_uri()`


    ```{.pl}
    $uri = $gitlab->create_uri($template, $arguments);
    $uri = $gitlab->create_uri($template, $arguments);
    ```


    Constructs an [URI](https://metacpan.org/pod/URI) instance for the template using given arguments.
    Constructs an [URI](https://metacpan.org/pod/URI) instance for the template using given arguments.


- decode\_data()
- `decode_data()`


    ```{.pl}
    $data = $gitlab->decode_data($response);
    $data = $gitlab->decode_data($response);
    ```


    Decodes the JSON content from the `$response` and converts it to Perl data.
    Decodes the JSON content from the `$response` and converts it to Perl data.


- exec\_request()
- `exec_request()`


    ```{.pl}
    $data = $gitlab->exec_request($template, $arguments);
    $data = $gitlab->exec_request($template, $arguments);


    # if arguments contain {-response => 1}
    # if arguments contain {-response => 1}
    ($data, $response) = $gitlab->exec_request($template, $arguments);
    ($data, $response) = $gitlab->exec_request($template, $arguments);
    ```


    Sends a request constructed from the given `$template` and `$arguments` hashref.
    Sends a request constructed from the given `$template` and `$arguments` hashref.
    Arguments that start with `-` (minus) are reserved to modify the client's behaviour and are **never** forwarded to GitLab.
    Arguments that start with `-` (minus) are reserved to modify the client's behaviour and are **never** forwarded to GitLab.
@@ -136,23 +160,27 @@ The following methods are intended to be called from additional methods implemen
    Returns data received from GitLab API, either as hashref or arrayref (this depends on the request) or `undef` if the request failed (and `die_on_error` is disabled).
    Returns data received from GitLab API, either as hashref or arrayref (this depends on the request) or `undef` if the request failed (and `die_on_error` is disabled).
    Additionally it saves the last [HTTP::Response](https://metacpan.org/pod/HTTP::Response) object as the `response` attribute of `$self`.
    Additionally it saves the last [HTTP::Response](https://metacpan.org/pod/HTTP::Response) object as the `response` attribute of `$self`.


    The following arguments can be used to modify ["exec\_request"](#exec_request)'s behaviour:
    The following arguments can be used to modify [`exec_request`](#exec_request)'s behaviour:


    - `-response => [0|1]`
    - `-response => [0|1]`


        Return both data and the [HTTP::Response](https://metacpan.org/pod/HTTP::Response) object as a list of two elements if set to true value.
        Return both data and the [HTTP::Response](https://metacpan.org/pod/HTTP::Response) object as a list of two elements if set to true value.


        ```{.pl}
        my ($data, $response) = $gitlab->$method(..., -response => 1);
        my ($data, $response) = $gitlab->$method(..., -response => 1);
        ```


    - `-immortal => [0|1]`
    - `-immortal => [0|1]`


        When enabled, calls will not not carp on error even when `die_on_error` is enabled.
        When enabled, calls will not not carp on error even when `die_on_error` is enabled.
        Recommended with `-response` option so that the status code can be inspected directly.
        Recommended with `-response` option so that the status code can be inspected directly.


        ```{.pl}
        my ($data, $response) = $gitlab->$method(..., -response => 1, -immortal => 1);
        my ($data, $response) = $gitlab->$method(..., -response => 1, -immortal => 1);
        if (!$response->is_success) {
        if (!$response->is_success) {
            # handle the error
            # handle the error
        }
        }
        ```


    - `-page => N`
    - `-page => N`


@@ -164,14 +192,18 @@ The following methods are intended to be called from additional methods implemen


# Package methods
# Package methods


- methods()
- `methods()`


    ```{.pl}
    $methods = GitLab::API::methods();
    $methods = GitLab::API::methods();
    ```


    Returns an arrayref of method names registered with the API.
    Returns an arrayref of method names registered with the API.
    This method cannot be exported, use
    This method __cannot__ be exported, use


    ```{.pl}
    GitLab::API::methods()
    GitLab::API::methods()
    ```


    to obtain the result.
    to obtain the result.


@@ -179,41 +211,46 @@ The following methods are intended to be called from additional methods implemen


Request methods are methods that create requests and call GitLab API.
Request methods are methods that create requests and call GitLab API.
This package provides an easy data-driven way to create such methods with
This package provides an easy data-driven way to create such methods with
request templates (see ["REQUEST TEMPLATES"](#request-templates) section and ["register"](#register)
request templates (see ["REQUEST TEMPLATES"](#request-templates) section and [`register`](#register)
method below).
method below).


Unless specified otherwise, these methods take a hash of options, e.g.
Unless specified otherwise, these methods take a hash of options, e.g.


```{.pl}
$gitlab->$method(key => value, ...);
$gitlab->$method(key => value, ...);
```


Generally, keys starting with the `-` (minus) characters are intended to modify the underlying `/exec_request`'s behaviour and are not forwarded to GitLab.
Generally, keys starting with the `-` (minus) characters are intended to modify the underlying `exec_request`'s behaviour and are not forwarded to GitLab.


This module contains only the ["whoami"](#whoami) API method, other methods are provided
This module contains only the [`whoami`](#whoami) API method, other methods are provided
by additional `GitLab::*` modules.
by additional `GitLab::*` modules.


# REQUEST TEMPLATES
# REQUEST TEMPLATES


This section contains instruction on how to implement API request methods.
This section contains instruction on how to implement API request methods.
See [GitLab::Users](https://metacpan.org/pod/GitLab::Users) and [GitLab::Groups](https://metacpan.org/pod/GitLab::Groups) for examples.
See [`GitLab::Users`](pod-GitLab-Users.md) and [`GitLab::Groups`](pod-GitLab-Groups.md) for examples.


The requests are made by calling the ["exec\_request"](#exec_request) method with the following parameters:
The requests are made by calling the [`exec_request`](#exec_request) method with the following parameters:


    $tmpl       request template
| parameter  | description                           |
    $args       hashref of request arguments
| ---------- | ------------------------------------- |
| `$tmpl`    | request template                      |
| `$args`    | hashref of request arguments          |


The _request template_ is a hashref with the following keys:
The _request template_ is a hashref with the following keys:


    method      [required] GET, POST, PUT or DELETE
| key         | description                                                                    |
    path        [required] URL relative to the URL parameter given to constructor
| ----------- | -------------------------------------------------------------------------------|
    paginated   if set to true, the request will be repeated and results
| `method`    | **[required]** `GET`, `POST`, `PUT` or `DELETE` |
                concatented until all items are obtained
| `path`      | **[required]** URL relative to the URL parameter given to constructor |
    query       arrayref of paramters that should be passed as query string in the URL
| `paginated` |  if set to `true`, the request will be repeated and results concatented until all items are obtained` |
    required    arrayref of required arguments
| `query`     | arrayref of paramters that should be passed as query string in the URL |
    optional    optional arguments
| `required`  | arrayref of required arguments |
    ret         hashref of HTTP codes whose values will be used as status messages
| `optional`  | optional arguments |
| `ret`       | hashref of HTTP codes whose values will be used as status messages |


The `path` value can contain placeholders in the format `<name>`, e.g. `/groups/<gid>/projects/<projid>` is a path that contains placeholders `gid` and `projid`.
The `path` value can contain placeholders in the format `<name>`, e.g. `/groups/<gid>/projects/<projid>` is a path that contains placeholders `gid` and `projid`.
When processing the template, these placeholders will automatically become _required arguments_.
When processing the template, these placeholders will automatically become __required arguments__.


Arguments specified in the `query` are _not_ required by default, hence, if missing, they will not be included in the final URL.
Arguments specified in the `query` are _not_ required by default, hence, if missing, they will not be included in the final URL.


@@ -222,22 +259,26 @@ Additional arguments (those not mentioned in `query`) will be passed as the requ
Optional arguments can be specified by the `optional` key.
Optional arguments can be specified by the `optional` key.
The value of this key is an arrayref with strings.
The value of this key is an arrayref with strings.


As the name suggests, _required arguments_ must be provided, otherwise the ["exec\_request"](#exec_request) will croak.
As the name suggests, _required arguments_ must be provided, otherwise the [`exec_request`](#exec_request) will croak.


## Examples
## Examples


Consider the following template hashref:
Consider the following template hashref:


```{.pl}
my $user_by_id = {
my $user_by_id = {
    name        => "user_by_id",
    name        => "user_by_id",
    method      => "GET",
    method      => "GET",
    path        => "/users/<uid>",
    path        => "/users/<uid>",
    ret         => { 404 => "User not found" },
    ret         => { 404 => "User not found" },
};
};
```


Called as `$gitlab->exec_request($user_by_id, { uid => 10 })`, the method will replace `<uid>` placeholder with `10` and then it will call
Called as `$gitlab->exec_request($user_by_id, { uid => 10 })`, the method will replace `<uid>` placeholder with `10` and then it will call


```
GET .../api/v3/users/10
GET .../api/v3/users/10
```


with empty content.
with empty content.
The `uid` argument is required; the method will croak if it is not present.
The `uid` argument is required; the method will croak if it is not present.
@@ -247,18 +288,21 @@ For other status codes it will return the reason provided either by GitLab or un


Another example:
Another example:


```{.pl}
my $user_add_ssh_key = {
my $user_add_ssh_key = {
    name        => "user_add_ssh_key",
    name        => "user_add_ssh_key",
    method      => "POST",
    method      => "POST",
    path        => "/users/<uid>/keys",
    path        => "/users/<uid>/keys",
    required    => [ qw!title key! ],
    required    => [ qw!title key! ],
};
};
```


This request requires arguments `title`, `key` and `uid` (since it appears in the `path`).
This request requires arguments `title`, `key` and `uid` (since it appears in the `path`).
The latter argument will be substituted in the path, the former two will be passed in the body of the request.
The latter argument will be substituted in the path, the former two will be passed in the body of the request.


The third example uses pagination:
The third example uses pagination:


```{.pl}
my $groups  = {
my $groups  = {
    name        => "groups",
    name        => "groups",
    method      => "GET",
    method      => "GET",
@@ -266,39 +310,47 @@ The third example uses pagination:
    query       => [ qw!search! ],
    query       => [ qw!search! ],
    paginated   => 1,
    paginated   => 1,
};
};
```


When called, the request will be repeated with increasing `page` query value until all pages are returned.
When called, the request will be repeated with increasing `page` query value until all pages are returned.
These responses will be concatenated to a single one.
These responses will be concatenated to a single one.
The method will croak if any of the returned pages is not an array.
The method will croak if any of the returned pages is not an array.


In addition, the request _can_ have (but does not require) an argument `search` that will be passed in the query string (`...?search=$search`).
In addition, the request __can__ have (but does not require) an argument `search` that will be passed in the query string (`...?search=$search`).
In order to make this argument required, the template would have to contain the following key:
In order to make this argument required, the template would have to contain the following key:


```{.pl}
    # ...
    required    => [ qw!search! ],
    required    => [ qw!search! ],
```


as well.
as well.


## Registering methods
## Registering methods


- register()
- `register()`


    ```{.pl}
    GitLab::API->register($template, ...);
    GitLab::API->register($template, ...);
    ```


    Instead of modifying [GitLab::API](https://metacpan.org/pod/GitLab::API) source to add a new method, or writing wrapper subs like this:
    Instead of modifying `GitLab::API` source to add a new method, or writing wrapper subs like this:


    ```{.pl}
    sub my_method {
    sub my_method {
        my ($api, $args) = @_;
        my ($api, $args) = @_;
        return $api->exec_request($my_method_template, $args);
        return $api->exec_request($my_method_template, $args);
    }
    }
    ```


    for each request, the `register` method creates a convenience wrapper method in this package.
    for each request, the `register` method creates a convenience wrapper method in this package.
    The above example can be written as the following:
    The above example can be written as the following:


    ```{.pl}
    GitLab::API->register($my_method_template);
    GitLab::API->register($my_method_template);

    # ...
    # ...

    $api->my_method($args);
    $api->my_method($args);
    ```


    The method name is the same as `$my_method_template->{name}` attribute.
    The method name is the same as `$my_method_template->{name}` attribute.


@@ -306,7 +358,7 @@ as well.


# AUTHOR
# AUTHOR


Roman Lacko <[xlacko1@fi.muni.cz](https://metacpan.org/pod/xlacko1@fi.muni.cz)>
Roman Lacko <[`xlacko1@fi.muni.cz`](mailto:xlacko1@fi.muni.cz)>


# SEE ALSO
# SEE ALSO


@@ -314,8 +366,6 @@ Roman Lacko <[xlacko1@fi.muni.cz](https://metacpan.org/pod/xlacko1@fi.muni.cz)>


    Complete GitLab API v3 implementation with CLI support.
    Complete GitLab API v3 implementation with CLI support.


- [GitLab](https://metacpan.org/pod/GitLab)
- [GitLab](pod-GitLab.md)

        use GitLab LIST;


    Wrapper around [GitLab::API](https://metacpan.org/pod/GitLab::API) that loads all GitLab modules in the `LIST`.
    Wrapper around `GitLab::API`