Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a GitHub Gist with API?

Tags:

php

github

gist

api

By looking at GitHub Gist API, I understood that it is possible to create the Gist create for anonymous users without any API keys/authentication. Is it so?

I could not find answers to following questions:

  1. Are there any restrictions (number of gists) to be created etc?
  2. Is there any example that I can post the code from a form text input field to create a gist? I could not find any.

Thanks for any information about this.

like image 909
user966582 Avatar asked Sep 06 '13 22:09

user966582


People also ask

What is Gist API?

The Gists API enables the authorized user to list, create, update and delete the public gists on GitHub. Gists. List gists for the authenticated user. Create a gist. List public gists.

Can you make an API on GitHub?

If you want to use the GitHub REST API for personal use, you can create a personal access token. The REST API operations used in this article require repo scope for personal access tokens (classic) or, unless otherwise noted, read-only access to public repositories for fine-grained personal access tokens.


1 Answers

Yes.

From Github API V3 Documentation:

For requests using Basic Authentication or OAuth, you can make up to 5,000 requests per hour. For unauthenticated requests, the rate limit allows you to make up to 60 requests per hour.

For creating a gist, you can send a POST request as follows:

POST /gists

Here's an example I made:

<?php
if (isset($_POST['button'])) 
{    
    $code = $_POST['code'];

    # Creating the array
    $data = array(
        'description' => 'description for your gist',
        'public' => 1,
        'files' => array(
            'foo.php' => array('content' => 'sdsd'),
        ),
    );                               
    $data_string = json_encode($data);

    # Sending the data using cURL
    $url = 'https://api.github.com/gists';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    # Parsing the response
    $decoded = json_decode($response, TRUE);
    $gistlink = $decoded['html_url'];

    echo $gistlink;    
}
?>

<form action="" method="post">
Code: 
<textarea name="code" cols="25" rows="10"/> </textarea>
<input type="submit" name="button"/>
</form>

Refer to the documentation for more information.

like image 71
Amal Murali Avatar answered Oct 04 '22 05:10

Amal Murali