npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

beautapi

v0.0.4

Published

Manage your endpoints in elegant way. Built on top of fetch.

Readme

Beautapi

Manage your endpoints in elegant way. Built on top of fetch.

https://img.shields.io/npm/v/beautapi.svg Bower Code Climate Build Status

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.

Installation

NPM

npm install beautapi

Bower

bower install beautapi

Getting started

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.

Live examples

Node

Script tag

Documentation

Beautapi.parse(model[, config]) : Api

model (Object)

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.

config (Object)

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);
	})

Return (Object)

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:

params (Object)

It allows you to pass values to the endpoint

const Api = Beautapi.parse({
  "Posts": {
    "get":          "/posts/:id",
  }
})

Api.Posts.get({id: 10})
fetchConfig (Object)

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.

Return (Promise)

Fetch function return is returned (Promise).

Helpers

Helpers are little functions that you would probably use as Promise.then callbacks.

parseJSON

Parse response to JSON

Api.Post.get({id: 1}).then(Beautapi.helpers.parseJSON)

throwErrors

Throw error when response status is not 2xx

Api.Post.get({id: 1}).then(Beautapi.helpers.throwErrors)

mapTo

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))

decorateTo

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))

License

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.