• Stars
    star
    614
  • Rank 73,061 (Top 2 %)
  • Language
    CoffeeScript
  • Created almost 12 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A jQuery plugin for easy consumption of RESTful APIs

jQuery REST Client

v1.0.1

Summary

A jQuery plugin for easy consumption of RESTful APIs

Downloads

File Size Report

Original: 10314 bytes.
Minified: 5920 bytes.
Gzipped:  1376 bytes.

Features

  • Simple
  • Uses jQuery Deferred for Asynchonous chaining
  • Basic Auth Support
  • Helpful Error Messages
  • Memory Cache
  • Cross-domain Requests with XDomain

Basic Usage

  1. Create a client.
  2. Construct your API.
  3. Make requests.

First setup your page:

<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<!-- jQuery rest -->
<script src="http://jpillora.com/jquery.rest/dist/1/jquery.rest.min.js"></script>
<!-- WARNING: I advise not using this link, instead download and host this library on your own server as GitHub has download limits -->

<script>
  // Examples go here...
</script>

Hello jquery.rest

var client = new $.RestClient('/rest/api/');

client.add('foo');

client.foo.read();
// GET /rest/api/foo/
client.foo.read(42);
// GET /rest/api/foo/42/
client.foo.read('forty-two');
// GET /rest/api/foo/forty-two/

Retrieving Results (Uses jQuery's $.Deferred)

var client = new $.RestClient('/rest/api/');

client.add('foo');

var request = client.foo.read();
// GET /rest/api/foo/
request.done(function (data, textStatus, xhrObject){
  alert('I have data: ' + data);
});

// OR simply:
client.foo.read().done(function (data){
  alert('I have data: ' + data);
});

More Examples

Nested Resources
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.foo.add('baz');

client.foo.read();
// GET /rest/api/foo/
client.foo.read(42);
// GET /rest/api/foo/42/

client.foo.baz.read();
// GET /rest/api/foo/???/baz/???/
// ERROR: jquery.rest: Invalid number of ID arguments, required 1 or 2, provided 0
client.foo.baz.read(42);
// GET /rest/api/foo/42/baz/
client.foo.baz.read('forty-two',21);
// GET /rest/api/foo/forty-two/baz/21/
Basic CRUD Verbs
var client = new $.RestClient('/rest/api/');

client.add('foo');

// C
client.foo.create({a:21,b:42});
// POST /rest/api/foo/ (with data a=21 and b=42)
// Note: data can also be stringified to: {"a":21,"b":42} in this case, see options below

// R
client.foo.read();
// GET /rest/api/foo/
client.foo.read(42);
// GET /rest/api/foo/42/

// U
client.foo.update(42, {my:"updates"});
// PUT /rest/api/42/   my=updates

// D
client.foo.destroy(42);
client.foo.del(42);
// DELETE /rest/api/foo/42/
// Note: client.foo.delete() has been disabled due to IE compatibility
Adding Custom Verbs
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.foo.addVerb('bang', 'PATCH');

client.foo.bang({my:"data"});
//PATCH /foo/bang/   my=data
client.foo.bang(42,{my:"data"});
//PATCH /foo/42/bang/   my=data
Basic Authentication
var client = new $.RestClient('/rest/api/', {
  username: 'admin',
  password: 'secr3t'
});

client.add('foo');

client.foo.read();
// GET /rest/api/foo/
// With header "Authorization: Basic YWRtaW46c2VjcjN0"

Note: A window.btoa polyfill such as Base64.js will be required for this feature to work in IE6,7,8,9

Caching
var client = new $.RestClient('/rest/api/', {
  cache: 5, //This will cache requests for 5 seconds
  cachableMethods: ["GET"] //This defines what method types can be cached (this is already set by default)
});

client.add('foo');

client.foo.read().done(function(data) {
  //'client.foo.read' is now cached for 5 seconds
});

// wait 3 seconds...

client.foo.read().done(function(data) {
  //data returns instantly from cache
});

// wait another 3 seconds (total 6 seconds)...

client.foo.read().done(function(data) {
  //'client.foo.read' cached result has expired
  //data is once again retrieved from the server
});

// Note: the cache can be cleared with:
client.cache.clear();
Override Options
var client = new $.RestClient('/rest/api/');

client.add('foo', {
  stripTrailingSlash: true,
  cache: 5
});

client.foo.add('bar', {
  cache: 10,
});

client.foo.read(21);
// GET /rest/api/foo (strip trailing slash and uses a cache timeout of 5)

client.foo.bar.read(7, 42);
// GET /rest/api/foo/7/bar/42 (still strip trailing slash though now uses a cache timeout of 10)
Fancy URLs
var client = new $.RestClient('/rest/api/');

Say we want to create an endpoint /rest/api/foo-fancy-1337-url/, instead of doing:

client.add('foo-fancy-1337-url');

client['foo-fancy-1337-url'].read(42);
// GET /rest/api/foo-fancy-1337-url/42

Which is bad and ugly, we do:

client.add('foo', { url: 'foo-fancy-1337-url' });

client.foo.read(42);
// GET /rest/api/foo-fancy-1337-url/42
Query Parameters
var client = new $.RestClient('/rest/api/');

client.add('foo');

client.foo.read({bar:42});
// GET /rest/api/foo/?bar=42

client.foo.create({ data:7 }, { bar:42 });
// POST /rest/api/foo/?bar=42 with body 'data=7'

client.foo.read({ data:7 }, { bar:42 });
// GET has no body!
// GET /rest/api/foo/?bar=42&data=7
Show API Example
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.add('bar');
client.foo.add('baz');

client.show();

Console should say:

ROOT: /rest/api/
  foo: /rest/api/foo/:ID_1/
    create: POST
    read: GET
    update: PUT
    delete: DELETE
    baz: /rest/api/foo/:ID_1/baz/:ID_2/
      create: POST
      read: GET
      update: PUT
      delete: DELETE
  bar: /rest/api/bar/:ID_1/
    create: POST
    read: GET
    update: PUT
    delete: DELETE
Simplify client
var client = new $.RestClient('/rest/api/');

client.add('forum');
client.forum.add('post');
client.forum.post.add('comment');

Instead of:

client.forum.post.comment.read(42,21,7);
client.forum.post.comment.update(42,21,7, {...});

You can do:

var comment = client.forum.post.comment;
comment.read(42,21,7);
comment.update(42,21,7, {...});
Global Client Example
$.client = new $.RestClient('/rest/api/');

// in another file...

$.client.add('foo');

Note: This is not best practise, use RequireJS, CommonJS or similar !

Method Override Header
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.foo.update(42);
// PUT /rest/api/foo/42/

client.add('bar', { methodOverride: true });
client.bar.update(42);
// POST /rest/api/bar/42/
// with header 'X-HTTP-Method-Override: PUT'
Singleton Resource Example
var client = new $.RestClient('/rest/api/');

client.add('foo');
client.foo.add('bar', { isSingle: true });
client.foo.bar.add('bazz');

client.foo.bar.bazz.read(42, 21);
// GET /rest/api/foo/42/bar/bazz/21/
//        'bar' has no id  ^

API

new $.RestClient( [ url ], [ options ] )

Instantiates and returns the root resource. Below denoted as client.

client.add( name, [ options ] )

Instaniates a nested resource on client. Internally this does another new $.RestClient though instead of setting it as root, it will add it as a nested (or child) resource as a property on the current client.

Newly created nested resources iterate through their options.verbs and addVerb on each.

Note: The url of each of these verbs is set to "".

See default options.verbs here.

client.addVerb( name, method, [ options ] )

Instaniates a new Verb function property on the client.

Note: name is used as the url if options.url is not set.

client.verb( [id1], ..., [idN], [data], [params])

All verbs use this signature. Internally, they are all essentially calls to $.ajax with custom options depending on the parent client and options.

ids must be a string or number.

data is a jQuery Ajax Options Object's data property. If ajax.data is set on the client this data will extend it.

params query parameters to be appended to the url

Note: A helpful error will be thrown if invalid arguments are used.

Options

The options object is a plain JavaScript option that may only contain the properties listed below.

See defaults here

Important: Both resources and verbs inherit their parent's options !

cache

A number representing the number of seconds to used previously cached requests. When set to 0, no requests are stored.

cachableMethods

An array of strings representing the HTTP method types that can be cached. Is ["GET"] by default.

verbs

A plain object used as a name to method mapping.

The default verbs object is set to:

{
  'create': 'POST',
  'read'  : 'GET',
  'update': 'PUT',
  'delete': 'DELETE'
}

For example, to change the default behaviour of update from using PUT to instead use POST, set the verbs property to { update: 'POST' }

url

A string representing the URL for the given resource or verb.

Note: url is not inherited, if it is not set explicitly, the name is used as the URL.

stringifyData

When true, will pass all POST data through JSON.stringify (polyfill required for IE<=8).

stripTrailingSlash

When true, the trailing slash will be stripped off the URL.

username and password

When both username and password are set, all ajax requests will add an 'Authorization' header. Encoded using btoa (polyfill required not non-webkit).

ajax

The jQuery Ajax Options Object

methodOverride

When true, requests (excluding HEAD and GET) become POST requests and the method chosen will be set as the header: X-HTTP-Method-Override. Useful for clients and/or servers that don't support certain HTTP methods.

request

The function used to perform the request (must return a jQuery Deferred). By default, it is:

request: function(resource, options) {
  return $.ajax(options);
}

isSingle

When true, resource is perceived as singleton:

See Singleton Resource Example

autoClearCache

When false, non-cachable requests (PUT, POST or DELETE - those not in cachableMethods) won't automatically clear the request's entry in the cache.

Note: Want more options ? Open up a New Feature Issue above.


Conceptual Overview

This plugin is made up nested 'Resource' classes. Resources contain options, child Resources and child Verbs. Verbs are functions that execute various HTTP requests. Both new $.RestClient and client.add construct new instances of Resource, however the former will create a root Resource with no Verbs attached, whereas the latter will create child Resources with all of it's options.verbs attached.

Since each Resource can have it's own set of options, at instantiation time, options are inherited from parent Resources, allowing one default set of options with custom options on child Resources.

Todo

  • CSRF
  • Add Tests

Contributing

See CONTRIBUTING.md

Change Log

  • v1.0.0 - Stable v1. Added isSingle and autoClearCache by @stalniy
  • v0.0.6 - Added methodOverride option
  • v0.0.5 - Minor bug fixes
  • v0.0.4 - Simplified API
  • v0.0.3 - Added into the jQuery Plugin Repo
  • v0.0.2 - Bug fixes
  • v0.0.1 - Beta Version

githalytics.com alpha

MIT License

Copyright © 2014 Jaime Pillora [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.

Analytics

More Repositories

1

chisel

A fast TCP/UDP tunnel over HTTP
Go
12,490
star
2

cloud-torrent

☁️ Cloud Torrent: a self-hosted remote torrent client
Go
5,744
star
3

xdomain

A pure JavaScript CORS alternative
JavaScript
3,072
star
4

overseer

Monitorable, gracefully restarting, self-upgrading binaries in Go (golang)
Go
2,276
star
5

notifyjs

Notify.js - A simple, versatile notification library
1,903
star
6

xhook

Easily intercept and modify XHR request and response
HTML
983
star
7

webproc

Wrap any program in a simple web-based user-interface
Go
725
star
8

docker-dnsmasq

dnsmasq in a docker container, configurable via a simple web UI
Dockerfile
723
star
9

go-tcp-proxy

A small TCP proxy written in Go
Go
694
star
10

backoff

Simple backoff algorithm in Go (golang)
Go
627
star
11

ipfilter

A package for IP Filtering in Go (golang)
Go
386
star
12

node-edit-google-spreadsheet

A simple API for editing Google Spreadsheets
JavaScript
304
star
13

base64-encoder

Base64 Encoder
HTML
260
star
14

installer

One-liner for installing binaries from Github releases
Go
200
star
15

node-torrent-cloud

Torrent Cloud – A self-hosted Bittorrent client in the Cloud
JavaScript
183
star
16

velox

Real-time Go struct to JS object synchronisation over SSE and WebSockets
Go
180
star
17

grunt-aws

A Grunt interface into the Amazon Node.JS SDK
JavaScript
174
star
18

opts

A Go (golang) package for building frictionless command-line interfaces
Go
162
star
19

verifyjs

Verify.js - A powerful, customizable asynchronous validation library
JavaScript
159
star
20

ssh-tron

Multiplayer Tron over SSH, written in Go
Go
143
star
21

go-ogle-analytics

Monitor your Go (golang) servers with Google Analytics
HTML
133
star
22

cloud-gox

A Go (golang) Cross-Compiler in the cloud
Go
132
star
23

media-sort

Automatically organise your movies and tv series
Go
118
star
24

go-tld

TLD Parser in Go
Go
114
star
25

node-load-tester

Simple load testing with Node.js
JavaScript
88
star
26

sshd-lite

A feature-light sshd(8) for Windows, Mac, and Linux written in Go
Go
85
star
27

csv-to-influxdb

Import CSV files into InfluxDB
Go
81
star
28

node-logbook

A simple, unobtrusive logger for Node
JavaScript
61
star
29

spy

Spy - Watches for file changes, restarts stuff
Go
61
star
30

go-and-ssh

Go and the Secure Shell protocol
Go
58
star
31

node-glob-all

Provide multiple patterns to node-glob
JavaScript
57
star
32

serve

Your personal HTTP file server in Go
Go
53
star
33

go-sandbox

An alternate frontend to the Go Playground
JavaScript
52
star
34

scraper

A dual interface Go module for building simple web scrapers
Go
50
star
35

node-google-sheets

Google Sheets v4 API using Node.js
JavaScript
44
star
36

dedup

A cross platform command-line tool to deduplicate files, fast
Go
42
star
37

archive

Archiver is a high-level API over Go's archive/tar,zip
Go
33
star
38

icmpscan

ICMP scan all hosts across a given subnet in Go (golang)
Go
29
star
39

hashedpassword

A small Go (Golang) package for hashed passwords
Go
26
star
40

gswg-examples

Getting Started with Grunt - Code Examples
JavaScript
25
star
41

webfont-downloader

A small web service which converts webfonts into zip archives
Go
24
star
42

aoc-in-go

A template repository for rapidly writing Advent of Code solutions in Go
Go
21
star
43

conncrypt

Symmetrically encrypt your Go net.Conns
Go
19
star
44

s3hook

Transparent Client-side S3 Request Signing
JavaScript
19
star
45

grunt-source

Reuse a Grunt environment across multiple projects
JavaScript
18
star
46

docker-cloud-torrent-openvpn

cloud-torrent and OpenVPN in a docker container
Shell
17
star
47

longestcommon

Longest common prefix/suffix across of list of strings in Go (Golang)
Go
16
star
48

mega-stream

Stream media content from Mega
JavaScript
14
star
49

node-gitlab-deploy

Deploy a Node server via a Gitlab Webhook
JavaScript
13
star
50

go-template

An automatic cross-compiling Go (golang) repository template using goreleaser and Github actions
Shell
13
star
51

ansi

Easy to use ANSI control codes
Go
12
star
52

subfwd

URL shortening via sub-domains, written in Go
HTML
12
star
53

js-play

A JavaScript playground/sandbox for learning, testing and prototyping
CSS
12
star
54

upnpctl

A small UPnP client
Go
11
star
55

go-echo-server

View your requests in JSON format
Go
10
star
56

node-echo-server

Responds with the JSONified Request
JavaScript
10
star
57

ddns-daemon

A Simple Dynamic DNS Daemon using Node.js and Route53
JavaScript
10
star
58

whos-home

ARP scan your subnet and POST findings
Go
10
star
59

uploader

A small server to receive files over HTTP
JavaScript
9
star
60

dynflare

DynamicDNS using Cloudflare
Go
9
star
61

pnode

peer-to-peer dnode over anything!
JavaScript
9
star
62

go433

Send and receive 433 MHz using a RaspberryPi and Go
Go
9
star
63

sockfwd

Forward a unix socket to a tcp socket
Go
9
star
64

vip

An IPv4 addressing Go (golang) module, based on uint32 instead of []byte
Go
8
star
65

ipflare

Find your public IP address according to Cloudflare
Go
8
star
66

node-ssh-http-agent

An HTTP agent for tunnelling through SSH connections
JavaScript
7
star
67

eventsource

An eventsource event encoder in Go (golang)
Go
7
star
68

sizestr

Pretty print byte counts in Go
Go
7
star
69

docker-caddy

Caddy in a docker container, configurable via a simple web UI
Dockerfile
7
star
70

sleep-on-lan

Send your computer to sleep via HTTP
JavaScript
7
star
71

requestlog

Simple request logging in Go (golang)
Go
6
star
72

pnode-store

A synchronized data store between connected Node.js applications
JavaScript
6
star
73

castlebot

🏰 A bot for your castle
Go
5
star
74

docker-vpn

Dockerized SoftEther VPN with a Web GUI
Shell
5
star
75

node-imdb-sort

Sort files based on IMDB data
CoffeeScript
5
star
76

jquery.prompt

Styled text prompts any element
CoffeeScript
5
star
77

gswg-io

Getting Started with Grunt - Homepage
HTML
5
star
78

compilejs

A mini Grunt.js for the browser
CoffeeScript
5
star
79

go-realtime

Keep your Go structs in sync with your JS objects
JavaScript
4
star
80

md-tmpl

Simple markdown templating using shell commands
Go
4
star
81

cookieauth

Cookie-based Basic-Authentication HTTP middleware for Go (golang)
Go
4
star
82

maplock

A map of locks in Go
Go
4
star
83

opts-examples

A Go (golang) package for building frictionless command-line interfaces
Go
4
star
84

go-mime

Extends pkg/mime with embedded mime types
Go
4
star
85

tranquil

Generate powerful RESTful JSON APIs
CoffeeScript
3
star
86

ipmath

IP Address Math in Go (golang)
Go
3
star
87

xtls

TLS utils
Go
3
star
88

puzzler

A programming puzzle framework in Go
Go
3
star
89

goff

Concatenate audio files, built with Go and FFmpeg
Go
3
star
90

prettyprinter

Simple Pretty Printer using Google's Prettify
HTML
3
star
91

github-badge-maker

Github Badge Maker
JavaScript
3
star
92

opts-talk

A talk on opts, for the Sydney Go Meetup
Go
3
star
93

grunt-source-web

A Grunt Source project to build optimized static websites
CoffeeScript
3
star
94

playground

Next version of https://js.jpillora.com
2
star
95

node-king

The king of your nodes - A powerful command and control center for your server infrastructure
JavaScript
2
star
96

bookshelf

Your personal bookshelf
HTML
2
star
97

debator-lander

Interactive and transparent debates online
2
star
98

webscan

Scans the entire Web for particular server types and devices
2
star
99

xmlfmt

A pure Go streaming XML formatter
Go
2
star
100

vigilant

Simple CLI tool for running multiple CLI tools in the same process
JavaScript
2
star