Create a gist using XMLHttpRequest (or fetch!)

I use Github's gist service directly and indirectly almost daily. Indirect meaning it's the storage backend for a few of sites I use including, and mundi. But I've never used their API. Until yesterday!

The gist API is wide open in that it's CORS-enabled and allows gist creation anonymously, which is pretty nice and is one reason it's so widely used.

To create a gist, do a POST with a 'Content-Type' header set to 'application/json;charset=UTF-8' and a body with a specific object structure, stringified. Here's some code to do it:

var data = {  
  "description": "anonymous gist",
  "public": false,
  "files": {
    "file1.txt": {
      "content": "file content!"
var xhr = new XMLHttpRequest();"post", "", true);  
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');  
xhr.onload = function(e) {  
  // do stuff with the response, like show a link to the created gist

And here's an example page using a tweaked version to take the content of a form and store it as a gist.

So that's neat. In most browsers (sorry Safari), fetch can be used in place of XMLHttpRequest.

Of course, after playing around with stuff I found the much more robust github.js which is probably what you want if you need to do more than create a gist. Still, this was a fun little afternoon detour.