• Stars
    star
    146
  • Rank 252,769 (Top 5 %)
  • Language
    JavaScript
  • Created over 7 years ago
  • Updated almost 7 years ago

Reviews

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

Repository Details

๐Ÿ”ง Generate a static JSON API from a tree of directories and files

Pluma logo

npm (scoped) JavaScript Style Guide Build Status

Static API generator is a Node.js application that creates a basic JSON API from a tree of directories and files. Think of a static site generator, like Jekyll or Hugo, but for APIs.

It takes your existing data files, which you may already be using to feed a static site generator or similar, and creates an API layer with whatever structure you want, leaving the original files untouched. Static API generator helps you deliver your data to client-side applications or third-party syndication services.

Couple it with services like GitHub Pages or Netlify and you can serve your API right from the repository too. ๐Ÿฆ„



1. Installation

  • Install via npm

    npm install static-api-generator --save
  • Require the module and create an API

    const API = require('static-api-generator')
    const api = new API(constructorOptions)

2. Usage

Imagine the following repository holding data about movies, organised by language, genre and year. Information about each movie will be in its own YAML file named after the movie.

input/
โ”œโ”€โ”€ english
โ”‚   โ”œโ”€โ”€ action
โ”‚   โ”‚   โ”œโ”€โ”€ 2016
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ deadpool.yaml
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ the-great-wall.yaml
โ”‚   โ”‚   โ””โ”€โ”€ 2017
โ”‚   โ”‚       โ”œโ”€โ”€ logan.yaml
โ”‚   โ”‚       โ””โ”€โ”€ the-fate-of-the-furious.yaml
โ”‚   โ””โ”€โ”€ horror
โ”‚       โ””โ”€โ”€ 2017
โ”‚           โ”œโ”€โ”€ alien-covenant.yaml
โ”‚           โ””โ”€โ”€ get-out.yaml
โ””โ”€โ”€ portuguese
    โ””โ”€โ”€ action
        โ””โ”€โ”€ 2016
            โ””โ”€โ”€ tropa-de-elite.yaml

2.1. Initialisation

Create an API by specifying its blueprint, so that the static API generator can understand how the data is structured, and the directory where the generated files should be saved.

const moviesApi = new API({
  blueprint: 'source/:language/:genre/:year/:movie',
  outputPath: 'output'
})

2.2 Generating endpoints

The following will generate and endpoint for each movie (e.g. /english/action/2016/deadpool.json).

moviesApi.generate({
  endpoints: ['movie']
})

Endpoints can be created for any data level. The following creates additional endpoints at the genre level (e.g. /english/action.json).

moviesApi.generate({
  endpoints: ['genre', 'movie']
})

It's also possible to manipulate the hierarchy of the data by choosing a different root level. For example, one could generate endpoints for each genre without a separation enforced by language, its original parent level. This means being able to create endpoints like /action.json (as opposed to /english/action.json), where all action movies are listed regardless of their language.

moviesApi.generate({
  endpoints: ['genre', 'movie'],
  root: 'genre'
})

3. API

3.1. Constructor

const API = require('static-api-generator')
const api = new API({
  addIdToFiles: Boolean,
  blueprint: String,
  pluralise: Boolean,
  outputPath: String
})

The constructor method takes an object with the following properties.


  • addIdToFiles

    Whether to add an id field to uniquely identify each data file. IDs are generated by computing an MD5 hash of the full path of the file.

    Default:

    false

    Example result:

    "review_id": "96a9b996439528ecb9050774c3e79ff2"


  • blueprint

    Required. A path describing the hierarchy and nomenclature of the data. It should start with a static path to the directory where all the files are located, followed by the name of each data level (starting with a colon).

    For the pluralise option to work well, the names of the data levels should be singular (e.g. languages vs. language)

    Example:

    'input/:language/:genre/:year/:movie'


  • outputPath

    Required. The path to the directory where endpoint files should be created.

    Example:

    'output'


  • pluralise

    The name of each data level (e.g. "genre") is used in the singular form when identifying a single entity (e.g. {"genre_id": "12345"}) and in the plural form when identifying a list of entities (e.g. {"genres": [...]}). That behaviour can be disabled by setting this property to false.

    Default:

    true


3.2. Method: generate

api.generate({
  endpoints: Array,
  entriesPerPage: Number,
  index: String,
  levels: Array,
  root: String,
  sort: Object
})

The generate method creates one or more endpoints. It takes an object with the following properties.


  • endpoints

    The names of the data levels to create individual endpoints for, which means generating a JSON file for each file or directory that corresponds to a given level.

    Default:

    []

    Example:

    ['genre', 'movie']


  • entriesPerPage

    The maximum number of entries (data files) to include in an endpoint file. If the number of entries exceeds this number, additional endpoints are created (e.g. /action.json, /action-2.json, etc.).

    Default:

    10

    Example:

    3


  • index

    The name of the main/index endpoint file.

    Default:

    The pluralised name of the root level (e.g. languages).

    Example:

    languages (generates languages.json)


  • levels

    An array containing the names of the levels to include in the endpoints. By default, an endpoint for a level will include all its child levels (e.g. an endpoint for a genre will have a list of years, which will have a list of movies). If a level is omitted (e.g. year), then all its entries are grouped together (i.e. an endpoint for a genre will have a list of all its movies, without any separation by year).

    Default:

    All levels

    Example:

    ['language', 'genre', 'movie']


  • root

    The name of the root level. When this doesn't correspond to the first level in the blueprint, the data tree is manipulated so that all entries become grouped by the new root level.

    Default:

    The name of the first level of the blueprint (e.g. language)

    Example:

    genre


  • sort

    An object that defines how the various data levels should be sorted. For levels corresponding to directories, an object with a single property (order) is expected, determining whether directory names are sorted from A-Z (ascending) or Z-A (descending).

    When levels contain entries, an additional property (field) defines what field of the data files should be used to sort the entries.

    Default:

    {} (directories will be sorted alphabetically from A-Z, entries will be sorted alphabetically from A-Z based on their filename)

    Example:

    {
      genre: {
        order: 'descending'
      },
      movie: {
        field: 'budget',
        order: 'descending'
      }
    }

4. Q&A

  • Why did you build this?

    GitHub has been the centrepiece of my daily workflow as a developer for many years. I love the idea of using a repository not only for version control, but also as the single source of truth for a data set. As a result, I created several projects that explore the usage of GitHub repositories as data stores, and I've used that approach in several professional and personal projects, including my own site/blog.

  • Couldn't Jekyll, Hugo or XYZ do the same thing?

    Possibly. Most static site generators are capable of generating JSON, but usually using awkward/brittle methods. Most of those applications were built to generate HTML pages and that's where they excel on. I tried to create a minimalistic and easy-as-it-gets way of generating something very specific: a bunch of JSON files that, when bundled together, form a very basic API layer.

  • Where can I host this?

    GitHub Pages is a very appealing option, since you could serve the API right from the repository. It has CORS enabled, so you could easily consume it from a client-side application using React, Angular, Vue or whatever you prefer. You could even use a CI service like Travis to listen for commits on a given branch (say master) and automatically run Static API Generator and push the generated output to a gh-pages branch, making the process of generating the API when data changes fully automated.

    Netlify is also very cool and definitely worth trying.

  • Would it be possible to add feature X, Y or Z?

    Probably. File an issue or, even better, a pull request and I'm happy to help. Bare in mind that this is a side project (one of too many) which I'm able to dedicate a very limited amount of time to, so please be patient and try to understand if I tell you I don't have the capacity to build what you're looking for.

  • Who designed the logo?

    The logo was created by Arthur Shlain from The Noun Project and it's licensed under a Creative Commons Attribution license.

More Repositories

1

include-media

๐Ÿ“ Simple, elegant and maintainable media queries in Sass
SCSS
2,571
star
2

staticman

๐Ÿ’ช User-generated content for Git-powered websites
JavaScript
2,413
star
3

compat-report

๐Ÿ”Œ A Developer Tools panel for flagging browser compatibility issues
JavaScript
117
star
4

buildtimes

โœ๏ธ Musings on building (and breaking) websites
JavaScript
88
star
5

popcorn

๐ŸŽฌ Demo of a Jekyll site using Staticman
HTML
85
star
6

include-media-export

๐Ÿ“ An include-media plugin for exporting breakpoints from Sass to JavaScript
JavaScript
72
star
7

inquirer-table-prompt

A table-like prompt for Inquirer
JavaScript
37
star
8

hugo-plus-staticman

โšก๏ธ Demo site using Hugo + Staticman
HTML
25
star
9

jekyll-social

Select what social media platforms to share your Jekyll blog posts on, right from the front matter.
21
star
10

jekyll-dynamic-menu

A Liquid snippet to generate markup for a dynamic navigation menu in Jekyll
HTML
19
star
11

postcss-cssential

๐Ÿšฉ PostCSS plugin to identify annotated blocks of critical CSS and inline them into a page
JavaScript
19
star
12

haiku

๐Ÿš€ Instant Heroku deploys from GitHub branches
JavaScript
16
star
13

include-media-columns

An include-media plugin for generating grid classes based on the BEMIT naming convention
CSS
16
star
14

gitemon

๐Ÿ‘พ Gotta Catch 'Em All!
JavaScript
16
star
15

wp-api-post-groups

A WP-API extension that allows multiple groups of posts with different filters to be obtained in a single request
PHP
15
star
16

eleventy-blog-staticman

A starter repository for a blog web site using the Eleventy static site generator and Staticman.
HTML
10
star
17

grunt-sass-import

A Grunt module for importing Sass partials with (some very basic) notion of source order
JavaScript
10
star
18

staticman-recaptcha

๐Ÿ‘ฎโ€โ™‚๏ธ Demo site using Staticman + reCAPTCHA
CSS
10
star
19

movies-api

๐ŸŽž Demo API using static-api-generator
JavaScript
9
star
20

homebridge-toggle-switch

Toggle switch for Homebridge
JavaScript
6
star
21

include-media-hidden-classes

๐Ÿ“ An include-media plugin to generate classes for hiding elements
CSS
6
star
22

notification-bus

๐ŸšŒ A Node.js library for loading and rendering notifications from a remote API
TypeScript
6
star
23

find-types

๐Ÿ” Find which of your module's dependencies have TypeScript types available
JavaScript
6
star
24

scheduled-netlify-deploys

Trigger Netlify deploys on a schedule
TypeScript
5
star
25

new-function

โœจ A tiny utility for creating a new Netlify Function.
JavaScript
4
star
26

staticman.net

๐Ÿ’ช Staticman website
SCSS
4
star
27

js-promise-queue

๐ŸŽข Runs JavaScript Promises in a queue
JavaScript
3
star
28

denis

A friendly DNS management bot for Slack
JavaScript
3
star
29

todo-api

๐Ÿ“‹ A RESTful API for a to-do list application built with DADI API
JavaScript
2
star
30

homebridge-arlo-basestation

Homebridge plugin for integrating Arlo with HomeKit
JavaScript
2
star
31

ok-to-test-action

2
star
32

next-netlify-starter-2

JavaScript
2
star
33

component-tree-webpack-plugin

A Webpack plugin for creating a simple tree of component dependencies
JavaScript
2
star
34

netlifind

Shell
2
star
35

codepen-scraper

JavaScript
1
star
36

next-netlify-starter

JavaScript
1
star
37

node-github-wrapper

JavaScript
1
star
38

mdn-speedtracker

JavaScript
1
star
39

preact-jsx-chai-match-template

๐Ÿ—œ A method that adds assertions with html-looks-like to Chai for testing Preact components
JavaScript
1
star
40

signally-case

1
star
41

jekyll-discuss-php

(UNMAINTAINED) A commenting system for Jekyll
PHP
1
star