Skip to content

Api class details

Miloslav Hůla edited this page May 15, 2014 · 11 revisions

Milo\Github\Api class constructor accepts Milo\Github\Http\IClient optionally. Usually you don't need it untill you use a CachedClient for example. Read about clients on another wiki page.

Most important methods of the class are Api::delete(), Api::get(), Api::head(), Api::patch(), Api::post() and Api::put(). These you need to Github API access and all of them returns Milo\Github\Http\Response. Following example shows other handy methods:

$api = new Milo\Github\Api;

# Set OAuth token
$api->setToken($token);

# Get current HTTP client, handy to access Client::onRequest() and Client::onResponse()
$client = $api->getClient();

# Milo\Github\Http\Request factory
$request = $api->createRequest('GET', '/api/path', [], ['Content-Type' => '...'], '');

# Make request object manually
$request = new Milo\Github\Http\Request('GET', 'https://github.com/v3/api/path', [...]);

# Response body decoder (read below)
$data = $api->decode($response);

Encoding data to JSON

If you pass array or object to Api::get(), Api::post() ... method as a content, method performs encoding to JSON and sets the Content-Type header for you. If you pass raw content as a string, it is up to you set proper header.

$gist = [
    'description' => 'API test',
    'private' => TRUE,
    'files' => [
        'test1.txt' => [
            'content' => 'This is a milo/github-api test ' . time(),
        ],
        'test2.txt' => [
            'content' => 'This is a milo/github-api test ' . time(),
        ],
    ],
];
$response = $api->post('/gists', $gists);

# But
$json = json_encode($gists);
$response = $api->post('/gists', $json, [], ['Content-Type' => 'application/json']);

Response content decoding

Method Api::decode() decodes the response. It checks response headers, if it is a JSON it performs a JSON decoding and it returns decoded structure. If it isn't JSON, it returns raw content (e.g. HTML).

URL parameters substitution

Github API documentation page uses URL path with parameters like :repo or :owner. You can use it. All parameters are poped from $parameters argument and replaced in URL. The rest is used in URL query.

# URL will be /users/milo/repos?type=owner
$response = $api->get('/users/:user/repos', [
    'user' => 'milo',
    'type' => 'owner'
]);

# The same without substitution
$response = $api->get('/users/milo/repos', [
    'type' => 'owner'
]);
Clone this wiki locally