Example code for using The Grid API
Example code directory on Github
Dart
Authenticate and get user information
/* The MIT License (MIT)
Copyright (c) 2015 Tommi Enenkel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/// The TheGridTest library.
library TheGridTest;
import 'dart:io';
import "dart:async";
import 'package:oauth2/oauth2.dart' as oauth2;
/**
* This console app will authenticate you with TheGrid and fetch your user
* profile. No error handling is implemented. The app will print an URL
* to the console that you need to open in the browser. You then authorize
* your TheGrid app to use your users credentials to perform API calls.
* A callback will inform the application about the credentials and the
* app will perform the actual API call.
**/
main(List<String> arguments) async{
var env = Platform.environment;
// !!! Get these by registering an app at https://passport.thegrid.io
var identifier = env["THEGRID_APP_ID"];
if (identifier == null) {
identifier = ""; // put app id here
}
var secret = env["THEGRID_APP_SECRET"];
if (secret == null) {
secret = ""; // put secret here
}
if (identifier.isEmpty || secret.isEmpty) {
throw("You must register an app, and replace identifier and secret in the code!");
}
oauth2.Client client = await connect(identifier, secret);
// Once you have a Client, you can use it just like any other HTTP
var result = await client.read("https://passport.thegrid.io/api/user");
print(result);
exit(0);
}
oauth2.Client
connect(final String identifier, final String secret) async{
final authorizationEndpoint =
Uri.parse("https://passport.thegrid.io/login/authorize/");
final tokenEndpoint =
Uri.parse("https://passport.thegrid.io/login/authorize/token");
final redirectUrl = Uri.parse("http://127.0.0.1:3000/");
File credentialsFile = new File(".credentials.json");
bool credentialsExist = await credentialsFile.exists();
var client = null;
if (credentialsExist) {
String json = await credentialsFile.readAsString();
var credentials = new oauth2.Credentials.fromJson(json);
client = new oauth2.Client(identifier, secret, credentials);
}
else
{
// If we don't have OAuth2 credentials yet, we need to get them
var grant = new oauth2.AuthorizationCodeGrant(
identifier, secret, authorizationEndpoint, tokenEndpoint);
String authUrl = grant.getAuthorizationUrl(redirectUrl, scopes:["website_management", "content_management", "update_profile"]);
print('Open browser and authenticate: ${authUrl}\n');
HttpServer server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 3000);
Completer completer = new Completer();
server.listen((HttpRequest request) {
request.response.statusCode = HttpStatus.FOUND;
request.response.close();
if (completer != null) {
completer.complete(grant.handleAuthorizationResponse(request.uri.queryParameters));
completer = null;
}
});
client = await completer.future;
var file = await credentialsFile.open(mode: FileMode.WRITE);
await file.writeString(client.credentials.toJson());
await file.close();
}
return client;
}
Prerequisites
Install Dart
Run
git clone https://github.com/the-grid/apidocs.git cd apidocs/code-examples/dart pub get dart auth-getuser.dart
Python
Share a file
Command-line example for sharing files, including text, images etc
import os, sys, uuid, mimetypes
import requests
from requests_oauthlib import OAuth2Session
import flask
def debug(*things):
string = ' '.join(str(t) for t in things)
sys.stderr.write(string+'\n')
# Note: No error handling
class TheGridAuth:
authorization_url = "https://passport.thegrid.io/login/authorize"
token_url = "https://passport.thegrid.io/login/authorize/token"
redirect_uri = 'http://localhost:3000/authenticated'
def __init__(self, _id, _secret, scopes=[]):
self.app_id = _id
self.app_secret = _secret
self.scopes = scopes
self.flask = flask.Flask(__name__)
# FIXME: implement loading token from disk
self.session = OAuth2Session(self.app_id, scope=self.scopes, redirect_uri=self.redirect_uri)
@self.flask.route("/authenticated", methods=["GET"])
def callback():
url = flask.request.url
token = self.session.fetch_token(self.token_url,
client_secret=self.app_secret,
authorization_response=url)
debug('/authenticated', 'got token')
try:
self.on_authenticated(self, token)
except Exception, e:
debug('ERROR', e)
return e
# FIXME: implement persistence of token to disk
return 'Authenticated, go back to program'
# Callback fired when we have been authicated
def on_authenticated(self, token):
print "%s Subclass or override this handler" % (__name__,)
def authenticate(self, *args, **kwargs):
authorization_url, state = self.session.authorization_url(self.authorization_url)
print "Open in browser to authenticate:\n %s" % (authorization_url,)
kwargs['port'] = 3000
self.flask.run(*args, **kwargs)
if __name__ == "__main__":
# Allow to use plain HTTP callback. Do not use on a production server
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1' # workaround for https://github.com/idan/oauthlib/pull/323
# !! Get these by registering an app at https://passport.thegrid.io
app_id = os.environ.get('THEGRID_APP_ID') or ""
app_secret = os.environ.get('THEGRID_APP_SECRET') or ""
scopes = ["content_management", "update_profile"]
auth = TheGridAuth(app_id, app_secret, scopes)
filepath = sys.argv[1]
filename = os.path.basename(filepath)
mimetype = mimetypes.guess_type(filename)[0]
files = {
'content': (filename, open(filepath, 'rb'), mimetype),
'type': mimetype,
'url': 'content://'+str(uuid.uuid4())
}
def upload_file(auth, token):
print 'Sharing file of type %s: %s' % (mimetype, filepath)
r = auth.session.post("https://api.thegrid.io/share", files=files)
if r.status_code == 202:
job = 'https://api.thegrid.io'+r.headers['location']
print 'Success: %s' % (job,)
r = auth.session.get(job)
print 'Job details: \n%s' % (r.content,)
else:
sys.stderr.write('ERROR: %s\n %s\n' % (r.status_code, r.content))
auth.on_authenticated = upload_file
auth.authenticate()
Prerequisites
Make sure you have Python 2.7 installed, as well as pip.
Install
git clone https://github.com/the-grid/apidocs.git cd apidocs/code-examples/python pip install -r requirements.pip -t ./
Run
python share-file.py ./myfile.png
CoffeeScript
Share a URL
https = require ‘https’
# Some configurations needed to talk with The Grid API
config =
host: 'api.thegrid.io'
port: 443
path: '/share'
# @url: http(s) URL to publicly available website
# @compress: true means share an article reference, false means import full page content
shareUrl = (url, compress, accessToken, callback) ->
# Data to be shared
data =
url: url
compress: compress
# Receive the token for this session at `accessToken`
jsonData = JSON.stringify data
opts =
host: config.host
port: config.port
path: config.path
method: 'POST'
headers:
Authorization: "Bearer #{accessToken}"
'Content-Type': 'application/json'
'Content-Length': jsonData.length
req = https.request opts, (res) =>
return callback res
req.write jsonData
req.end()
asyncSeries = (items, func, callback) ->
items = items.slice 0
results = []
next = () ->
if items.length == 0
return callback null, results
item = items.shift()
func item, (err, result) ->
return callback err if err
results.unshift result
return next()
next()
waitStdinEof = (callback) ->
data = ""
process.stdin.on 'data', (chunk) ->
data += chunk.toString()
process.stdin.on 'end', () ->
return callback null, data
exports.main = main = () ->
unless process.argv.length > 2
console.log "Usage: thegrid-share-url.coffee http://example.com/foo [nocompress]"
process.exit 1
url = process.argv[2]
nocompress = process.argv[3] and process.argv[3] != 'compress'
token = process.env.THEGRID_TOKEN
unless token
console.log 'Missing authentication token. Must be configured as environment variable THEGRID_TOKEN'
process.exit 2
shareOne = (u, cb) ->
shareUrl u, !nocompress, token, (res) ->
if res.statusCode > 202
return cb new Error "Error sharing: #{res.statusCode}"
console.log "Shared '#{u}': #{res.headers.location} import=#{nocompress}"
return cb null
onUrls = (err, urls) ->
asyncSeries urls, shareOne, (err) ->
throw err if err
console.log 'Done'
if url == '-'
waitStdinEof (err, data) ->
urls = data.split('\n').filter (u) -> u # remove trailing ''
onUrls err, urls
else
onUrls null, [url]
main() if not module.parent
Share a file
https = require “https” FormData = require “form-data” uuid = require “uuid” fs = require “fs”
shareFile = (filePath, accessToken, callback) ->
formData = new FormData()
# It's interesting to use a valid UUID to keep track of the shared item
# If you have a canonical URL, use that instead
formData.append "url", "content://#{uuid.v4()}"
formData.append "type", "image/jpeg" # FIXME: don't hardcode
formData.append "content", fs.createReadStream(filePath)
opts =
host: "api.thegrid.io"
port: 443
path: "/share"
method: "POST"
headers: formData.getHeaders()
# Add your `accessToken` to headers
opts.headers["Authorization"] = "Bearer #{accessToken}"
req = https.request opts
formData.pipe req
req.on "response", (result) ->
callback result
exports.main = main = () ->
unless process.argv.length > 2
console.log "Usage: coffee share-file.coffee myfile.png"
process.exit 1
fileToShare = process.argv[2]
token = process.env.THEGRID_TOKEN
unless token
console.log 'Missing authentication token. Must be configured as environment variable THEGRID_TOKEN'
process.exit 2
shareFile fileToShare, token, (res) ->
if res.statusCode > 202
console.log 'Error sharing '
process.exit 3
console.log "Finished sharing '#{fileToShare}': #{res.headers.location}"
main() if not module.parent
Prerequisites
Make sure you have NodeJS installed.
Install
git clone https://github.com/the-grid/apidocs.git cd apidocs/code-examples/coffeescript npm install
Run
To share an URL:
coffee share-url.coffee
To share a local file:
coffee share-file.coffee myfile.png