API Operations
A lightweight (5kb minified) library for simple RESTful API operations that leverages fetch
.
Features
- Minimal yet powerful API
- Uses the fetch standard so it returns promises and keeps things idiomatic
- Automatic parsing of JSON data; falls back to plain text
- Standardized errors by default or configure the error output to your taste
- Rejects by default on
response.status < 200 && response.status > 300
, but you can configure the validation to your needs
Installing
installing api-operations
via npm:
npm install api-operations
api-operations uses the fetch standard: you should bring your favorite polyfill ;D
(and fetch uses Promise, so you might need to polyfill that too, consult your polyfill of choice docs)
# official fetch polyfill - https://github.com/github/fetch npm install whatwg-fetch # node-fetch - https://github.com/bitinn/node-fetch npm install node-fetch # isomorphic-fetch - https://github.com/matthew-andrews/isomorphic-fetch npm install isomorphic-fetch
UMD build
you can get the development and minified production files on the 'dist' folder.
The library namespace is apiOperations
Getting started
// Simple get json from url // Simple post json to url // Creating an API source for quick and convenient useconst myAPISource = // Get from 'http://myCoolApi.com/resource/someEndpoint'myAPISource // Put to 'http://myCoolApi.com/resource/someOtherEndpoint'myAPISource // Get from 'http://myCoolApi.com/resource'myAPISource
API
-
- get
(url[, fetchOptions[, operationOptions]])
- getQuery
(url, query,[, fetchOptions[, operationOptions]])
- postJson
(url, body[, fetchOptions[, operationOptions]])
- putJson
(url, body[, fetchOptions[, operationOptions]])
- patchJson
(url, body[, fetchOptions[, operationOptions]])
- sendJson
(url, body[, fetchOptions[, operationOptions]])
- delete_
(url[, fetchOptions[, operationOptions]])
- createApiSource
(baseUrl[, baseFetchOptions[, baseOperationOptions]])
- get
Methods
statusValidator and errorParser definitions omitted from examples for clarity; check the Arguments > operationOptions section for details
(url[, fetchOptions[, operationOptions]])
get Gets a document using the 'get' HTTP method and returns a promise with a parsed result. Example:
(url, query[, fetchOptions[, operationOptions]])
getQuery Parses query object and gets a document using the 'get' HTTP method and returns a promise with a parsed result. This utility method is useful when you have complex query params that you don't want to just hardcore in the url Example:
// gets http://myCoolApi.com/endpoint?page=6&active=true
You can also append query params to the url if that's your thing
// gets http://myCoolApi.com/endpoint?foo=bar&page=6&active=true
(url, body[, fetchOptions[, operationOptions]])
postJson Sends a JSON body using the 'post' HTTP method and returns a promise with a parsed result. body gets converted to json automatically. Example:
(url, body[, fetchOptions[, operationOptions]])
putJson Sends a JSON body using the 'put' HTTP method and returns a promise with a parsed result. body gets converted to json automatically. Example:
(url, body[, fetchOptions[, operationOptions]])
patchJson Sends a JSON body using the 'patch' HTTP method and returns a promise with a parsed result. body gets converted to json automatically. Example:
(url, body[, fetchOptions[, operationOptions]])
sendJson Generic method to send a JSON body, it doesn't set any HTTP method by itself so it's useful if you want to use a non-standard/non-supported method or want to extend functionality. returns a promise with a parsed result. body gets converted to json automatically. Example:
(url[, fetchOptions[, operationOptions]])
delete_ Sends a request using the 'delete' HTTP method and returns a promise with a parsed result. Example:
// we use 'delete_' because 'delete' is a reserved keyword
(baseUrl, [baseFetchOptions[, baseOperationOptions]])
createApiSource Creates an 'API source' which acts as a base URL and base configurations for operations. Returns an object with the following endpoint methods:
- get
(endPoint[, fetchOptions[, operationOptions]])
- getQuery
(endPoint, query[, fetchOptions[, operationOptions]])
- postJson
(endPoint, body[, fetchOptions[, operationOptions]])
- putJson
(endPoint, body[, fetchOptions[, operationOptions]])
- patchJson
(endPoint, body[, fetchOptions[, operationOptions]])
- sendJson
(endPoint, body[, fetchOptions[, operationOptions]])
- delete
(endPoint[, fetchOptions[, operationOptionsions]])
All endpoint method options get merged with the base options created by createApiSource
// Creating an API source for quick and convenient useconst myAPISource = // Get from 'http://myCoolApi.com/someEndpoint' with 'same-origin' credentials,// custom statusValidator and errorParsermyAPISource // Post to 'http://myCoolApi.com/someOtherEndpoint' with 'same-origin' credentials,// connection 'keep-alive', custom statusValidator and errorParsermyAPISource // Get from 'http://myCoolApi.com/', with 'same-origin' credentials,// custom errorParser and specific statusValidatorconst statusValidator = status > 0 && status < 100 myAPISource
Arguments
url / baseUrl / endPoint
- url: a
string
containing a full url i.e.https://api.github.com/user/repos
- baseUrl: a
string
containing a root api url i.e.https://api.github.com/user
orhttps://api.github.com
- endPoint: a
string
containing an API endpoint i.e.repos
oruser/repos
fetchOptions
An object
containing options for the request. Directly passed to fetch
second argument.
this is the place to set headers, body, and other request data. Example:
method: 'post' headers: 'Accept': 'application/json' 'Content-Type': 'application/json' body: JSON
operationOptions
An object
that modifies the operations default behavior. The following key/values are supported:
-
dontParse
Boolean
: If true the response object will be passed as is. Useful when you need the response headers or metadata. Default is false.// Maybe you just need the headers// Or maybe you also need the parsed body -
statusValidator
(response_status)
: Afunction
that receives the response status code, implements some custom validation and returnstrue
for valid statuses andfalse
for invalid ones// A custom status validator that passes on status 0 to 100 and fails on everything elseconst statusValidator = status > 0 && status < 100// Use it! -
errorParser
(error, response)
: Afunction
that receives the parsed rejected response (error), the raw response object and returns an error response// A custom error parser that passes some custom dataconst errorParser = {const _error = 'Custom Error'_errorname = responsestatusText_errorresponse = response_errorbody = error_errormyExtraStuff = 'teach me how to dougie, teach me-teach me how to dougie~'return _error}// Use it!