Giter Site home page Giter Site logo

unio's Introduction

#unio

##One REST API Client for All.

The Unio client is an easily-extensible REST API Client that supports any REST API that can be described in JSON.

The initiative behind unio is to describe REST APIs in a simple, readable JSON format. This allows them to be imported into unio, and it will know automatically how to talk to the web service from the JSON spec. You can simply import the spec, and start making requests to the API right away. This makes it easy for you to test, use and reuse REST APIs by saving you the time of writing an API client for every new service that pops up.

Currently, the APIs implemented out-of-the-box with unio are:

  • Facebook
  • Twitter
  • Github
  • Instagram
  • StackExchange

Feel free to fork and add new REST API specs! See the Facebook spec and the Instagram spec as examples.

#Install

npm install unio

#Usage

var unio = require('unio')

var client = unio()

//
// with the Facebook Search API
//
var params = {
    q: 'coffee',
    access_token: 'FB-ACCESS-TOKEN'
}

client
    .use('fb')
    .get('search', params, function (err, response, body) {
        console.log('first search result', body.data[0])
    })

//
// Make an FQL query
//
var params = {
    q: 'SELECT first_name, pic FROM user WHERE uid=588625709',
    access_token: 'FB-ACCESS-TOKEN'
}

client
    .use('fb')
    .get('fql', params, function (err, res, body) {
        console.log('results:', body.data)
    })

//
// Use the Twitter Search API
//
var params = {
    q: 'banana',
    oauth: {
        consumer_key:       '...',
        consumer_secret:    '...',
        token:              '...',
        token_secret:       '...',
    }
}

client
    .use('twitter')
    .get('search/tweets', params, function (err, response, body) {
        console.log('search results:', body)
    })

//
// use the Twitter REST API to post a tweet
//
var params = {
    status: 'tweeting using unio! :)',
    oauth: {
        consumer_key:       '...',
        consumer_secret:    '...',
        token:              '...',
        token_secret:       '...',
    }
}

client
    .use('twitter')
    .post('statuses/update', params, function (err, res, body) {
        // ...
    })

//
// with the Instagram API
//
var params = {
    id: 'snow',
    access_token: 'INSTAGRAM-ACCESS-TOKEN'
}

client
    .use('instagram')
    .get('tags/:id/media/recent', params, function (err, res, body) {
        // ...
    })

//
// import a JSON spec from the local filesystem
//
client
    .spec('./path/to/json/file')
    .use('myspec')
    .post('blah', function (err, res, body) {
        // ...
    })

//
// add a new spec directly
//
var apiSpec = {
    name: 'api-name',
    api_root: 'http://api.something.com',
    resources: [
        {
            path: 'some/resource',
            methods: [ 'post' ],
            params: {
                foo: 'required',
                bar: 'optional'
            }
        },
        // other resource entries here...
    ]
}

// now use the newly added spec
client
    .spec(apiSpec)
    .use('api-name')
    .post('some/resource', { foo: 123 }, function (err, res, body) {
        // ...
    })

#API:

##.use(name)

Tells unio that the next request you make will be to the API whose spec has the name name. If you don't call .use() before making a request, it will default to the last API that you called .use() with.

##.spec(spec)

Adds a new REST API spec to the unio client. Spec can be:

  • an Object representing an API specification
  • an Array of API specifications
  • a String that is a path to a JSON file

The specs that unio currently supports out-of-the-box are in the specs folder. See the Facebook spec and the Twitter spec as examples.

##.get(resource, [ params, callback ])

GET an API resource, with optional params object for the request, and an optional callback that looks like: function (err, response, body) { ... }.

##.post(resource, [ params, callback ])

Same usage as .get(), but sends a POST request.

##.patch(resource, [ params, callback ])

Same usage as .get(), but sends a PATCH request.

##.put(resource, [ params, callback ])

Same usage as .get(), but sends a PUT request.

##.delete(resource, [ params, callback ])

Same usage as .get(), but sends a DELETE request.

##Defining a Unio Spec

unio is intended to make it as easy/painless as possible to talk to HTTP APIs. Here's an example of what a spec looks like:

{
    name: 'some-api',
    api_root: 'http://api.something.com',
    resources: [
        {
            path: 'users/:id',
            methods: [ 'get', 'put' ],
            params: {
                id: 'required'
            }
        },
        {
            path: 'notes',
            methods: [ 'post' ],
            params: {
                title: 'required',
                text: 'required',
                tags: 'optional'
            }
        }, 
        {
            name: 'friends',
            path: 'friends.json',
            methods: [ 'post' ],
            params: {
                id: 'required'
            }
        }  
        // other resource entries here...
    ]
}

###name (String)

Each unio spec must have a name. This allows you to .use() the spec and start making requests.

###api_root (String)

The api_root specifies the root url where the API resources are located.

###resources (Array)

Array of API resources.

##Defining a Resource

Each object in the resources array represents a REST API resource. For example, a GET user resource taking three optional parameters (id, name, and location) would look like this:

{
    path: 'user',
    methods: [ 'get' ],
    params: {
        id: 'optional',
        name: 'optional',
        location: 'optional'
    },
}

Each of the resource keys are described below:

####path (String)

URI where the resource is located, without a leading slash (e.g. posts/newest) or a full URL (e.g. https://api.bar.com).

####name (String)

Optional name of the resource. When you make a request with unio, for example with .get(resource, ...), you can specify the resource by its name value rather than by its path. Think of it like an alias path value for the resource.

E.g. If the following resource is specified:

{
    name: 'statuses/update',
    path: 'statuses/update.json',
    methods: [ 'post' ],
    params: {
        foo: 'required'
    }
}

You can then request the resource by specifying its name OR its path:

// GET a resource by specifying its `name`
unio()
    .use('...')
    .get('statuses/update', params, callback)

// GET a resource by specifying its `path`
unio()
    .use('...')
    .get('statuses/update.json', params, callback)

####methods (Array)

HTTP verbs that may be used to request the resource (allowed: "GET", "POST", "PUT", "DELETE", "PATCH").

####params (Object)

Object representing the parameters accepted by the resource. Each parameter must be marked "optional" or "required".


Running the tests

npm test

Other Implementations

See PyUnio by Mihir Singh (@citruspi) for a Python implementation of unio.

License

(The MIT License)

Copyright (c) by Tolga Tezel [email protected]

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.

unio's People

Contributors

citruspi avatar dstokes avatar jab416171 avatar ttezel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unio's Issues

/:params

Having a little trouble using :params in a quickie instagram spec.

I have the following in the spec:

    {
      "name": "tags/:id",
      "path": "tags/:id",
      "methods": [
        "get"
      ],
      "params": {
        "access_token": "required"
      }
    },
    {
      "name": "tags/:id/media/recent",
      "path": "tags/:id/media/recent",
      "methods": [
        "get"
      ],
      "params": {
        "min_id": "optional",
        "max_id": "optional",
        "access_token": "required"
      }
    },

But when I make the following request:

.get('tags/'+tag+'/media/recent', {'access_token':at}, function (err,resp,body) {

Unio seems to hit on "tags/:id" and not "tags/:id/media/recent".

Suggestions?

Add PATCH method

The PATCH method is used by Backbone.js apps to perform partial updates (where a PUT must describe the entire resource). It would be useful/easy to add this in.

Easier specs?

I was looking at how APIhub stores the JSON description of an API, and I was wondering if it would be worth it to use specs in that style? APIhub seems to have a decent many of them already mapped out. (Note: View it more easily here) At the very least, more specs could be crawled from that data. (If that's legal and morally okay).

Add PATCH method

The PATCH method is used by Backbone.js apps to perform partial updates (where a PUT must describe the entire resource). It would be useful/easy to add this in.

Twitter API V1 upgrade

Hi ttezel, when I try to use twitter from unio i get

[ { message: 'The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.',
code: 68 } ] }

Is it in pipeline twitter API update ?

Thanks!

Include expected response data in specification

Might it be benificial to include a json description of the expected data in the response?
This could make it possible to have a client user to supply callbacks to instantiate objects or parse response data.

Support defining request headers

Please add the ability to define custom request headers. This should support statically defined headers that are the same for every request, as well as headers that are required with dynamic values for each request (e.g. a custom header specifying a session ID), and headers that are defined to be present only for specific requests.

Add support for defining response errors in specs

For example consider the facebook api errors here.

We can easily map non-200 responses to create errors from the response body.

@ttezel should the callbacks be invoked with (err, res, body) where err would be an error with error message and body is the parsed response body, or attach the response body on the err object (err.body) and callback with (err, res)?

Make the default included specs similar in structure

eg. the github spec

{
    "name": "github",
    "api_root": "https://api.github.com",
    "resources": {
        "authorizations": {
            "path": "authorizations",
            "methods": [ "post", "get" ],
            "params": [
                {
                ....
}

has the resource name as 'key' to the resource 'object'.

however the twitter spec defines the resource name as part of the object.
Maybe it is nice to choose one format as reference for implementations of Unio in other languages? Maybe it might also be nice to have the specs complete for those included in Unio?

Suggestion for improving specs

I like the idea to write specs in JSON ๐Ÿ‘

Moreover, this can be used in a HTML web page as a documentation, just by parsing the JSON document in javascript and creating a complete and clean documentation.

But for that, I feel like the actual spec is missing some important key points, like the description of each resources and params.

Here an example of an opinion I have for adding description and then improving JSON description of REST API services :

{
    "name": "twitter",
    "api_root": "https://api.twitter.com/1.1",
    "resources": {
        "account/settings":{
            "path": "account/settings.json",
            "methods": [ "get" ],
            "description": "Returns settings (including current trend, geo and sleep time information) for the authenticating user.",
            "params": [
                {
                    "name": "oauth",
                    "state": "required",
                    "description": "OAuth token required to execute this request.",
                },
                {
                    "name": "count",
                    "state": "optional",
                    "description": "Specifies the number of tweets to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. We include retweets in the count, even if include_rts is not supplied. It is recommended you always send include_rts=1 when using this API method.",
                }
            ]
        },
    // ...
}

Doing this, even the author of this documentation can build a documentation in just a single html page that updates itself automatically when the documentation is updated! :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.