Manage your endpoints in elegant way. Built on top of fetch.
Beautapi is a small library that allows you to keep all endpoints in a single place and use them with pleasure. All you have to do is write down paths and configure api to your needs.
npm install beautapi
bower install beautapi
const Beautapi = require("beautapi");
const Fetch = require("node-fetch"); // NODE ENV: Node doesn't have window.fetch method.*
// Create api model
const model = {
Movies: {
getAll: "/movies",
get: "movies/:id",
create: ["/movies", { method: "POST" }]
}
};
// Configure Beautapi
const config = {
endpointPrefix: "http://api.myserver.com",
fetchReference: Fetch,
thenChain: [
Beautapi.helpers.throwErrors,
Beautapi.helpers.parseJSON
]
};
// Create api object
const Api = Beautapi.parse(model, config);
// Use it
Api.Movies.getAll().then();
Api.Movies.get({id: 12}).then();
Api.Movies.create({}, {
body: {name: "Titanic"}
}.then();
// Use it with class, like a boss
class MovieClass {
constructor({id, title, year}) {
this.id = id;
this.title = title;
this.year = year;
}
getTitle() {
return this.title;
}
}
Api.Movies.get({id: 10})
.then(Beautapi.helpers.decorateTo(MovieClass))
.then((movie) => { console.log(movie.getTitle()) })
.catch((err) => { console.error(err) })
*Most of modern browsers have fetch method, but it's a good idea to provide polyfill (for example https://github.com/github/fetch). If you want to run beautapi in node enviroment you have to provide special node-fetch polyfill.
Required
Model describes how api should look like. Beautapi will create endpoints based on model. It can be flat or multi-level object.
const Api = Beautapi.parse({
"Posts": {
"get": "/posts/:id",
"post": "/posts",
"put": "/posts/:id",
"patch": "/posts/:id",
"delete": "/posts/:id",
"getByUserId": ["/posts?userId=:userId", {"method": "GET"}],
"Comments": {
"get": "/posts/:id/comments"
}
}
})
// Api.Posts.get({id: 10}).then((response) => { ... })
// Api.Posts.getByUserId({id: 99}).then((response) => { ... })
// Api.Posts.Comments.get({id: 53}).then((response) => { ... })
If leaf is a string beautapi will create reuqest method using value as path and key as a method (case innsensitive) and name. It will match methods like "DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH". Otherwise "GET" will be used.
If leaf is an array beautapi will create request method using first value as path, second value as fetch config and key as a name.
Path can take parameters preceded by a colon.
Optional
Name | Type | Description | Default |
---|---|---|---|
endpointRegex | regex | Regex used to parsing endpoint parameters. | /(?:\:)([a-zA-Z]([a-zA-Z0-9]|-|_)*)/g |
endpointPrefix | string | String that will be added to every endpoint at the beginning. | "" |
fetchReference | function | Reference to the fetch function. If defined it will be used instead of default fetch function. | undefined |
fetchConfig | object | Config passed to fetch function. | {} |
thenChain | array[function] | Array of functions that will be passed as callback of Promise.then method. So you don't have to call them manually every time. | [] |
Example:
import fetch from "fetch";
const model = {
Users: {
search: ["/users/{keyword}", {method: "GET"}]
}
}
const parseJSON = function(response) {
return response.json()
}
const Api = Beautapi.parse(model, {
endpointRegex: /(?:\{)([a-zA-Z]([a-zA-Z0-9]|-|_)*)(?:\})/g
endpointPrefix: "http://localhost:3000",
fetchReference: fetch,
fetchConfig: {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
},
thenChain: [parseJSON]
})
//Usage
Api.Users.search({keyword: "admin123"}) // GET http://localhost:3000/users/admin123
// .then(parseJSON) will be called here because it has been added to thenChain array
.then((response) => {
console.log(response);
})
Returned object has the same structure as model, but instead of strings and arrays at leaf positions it has functions.
const Api = Beautapi.parse({
"Posts": {
"get": "/posts/:id",
"post": "/posts",
"getByUserId": ["/posts?userId=:userId", {"method": "GET"}],
"Comments": {
"get": "/posts/:id/comments"
}
}
})
// Api == {
// Posts: {
// get: function([params, fetchConfig]),
// post: function([params, fetchConfig]),
// getByUserId: function([params, fetchConfig]),
// Comments: {
// get: function([params, fetchConfig])
// }
// }
// }
Each function can take two parameters:
It allows you to pass values to the endpoint
const Api = Beautapi.parse({
"Posts": {
"get": "/posts/:id",
}
})
Api.Posts.get({id: 10})
It allows you to assign something (or override) to the fetch configuration for this single invocation.
const Api = Beautapi.parse(...);
const data = {
title: "Lorem ipsum",
text: "abc"
};
Api.Posts.post({}, {
body: data
});
Note that you don't have to stringify data object. Beautapi will convert it and it'll add Content-Type header.
Fetch function return is returned (Promise).
Helpers are little functions that you would probably use as Promise.then callbacks.
Parse response to JSON
Api.Post.get({id: 1}).then(Beautapi.helpers.parseJSON)
Throw error when response status is not 2xx
Api.Post.get({id: 1}).then(Beautapi.helpers.throwErrors)
It maps response array to class instances.
class Post {
constructor({id, userId, title, body}) {
this.id = id;
this.userId = userId;
this.title = title;
this.body = body;
this.length = title.length + body.length;
}
}
API.Posts.getAll().then(Beautapi.helpers.mapTo(Post))
Same as mapTo, but for single object (not array).
class Post {
constructor({id, userId, title, body}) {
this.id = id;
this.userId = userId;
this.title = title;
this.body = body;
this.length = title.length + body.length;
}
}
API.Posts.get({id: 1}).then(Beautapi.helpers.decorateTo(Post))
ISC
Copyright (c) 2016, Piotr Frącek
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.