Serving a JSON REST API without infrastructure thanks to Netlify

Standard

In this blog post, I’ll explain how to leverage Netlify and GitHub to create a REST API, serving JSON, without any infrastructure and for free. Netlify is amazing at deploying projects with continuous integration, a build step, static hosting behind a CDN and with automatic HTTPS support thanks to Let’s Encrypt. I’m using GitHub as my go-to hosted version control system, but you can use Gitlab or Bitbucket if you’d like.

Our project has some constraints:

  • The REST API will only be able to serve content, not create, update or delete things (we only have static hosting and not a server-side language) ;
  • You should have a reasonable amount of files to serve (a few hundreds);
  • You should respect Netlify’s Terms of Service. Quotas for free accounts: 100 GB / month of bandwidth, 100 GB of storage.

Example: an API for bank holidays

I’ll use a real-world example to explain things: we’re going to build a REST API for bank holidays. Basically, for a given year, we’ll tell which days are bank holidays. Here is the final GitHub repository.

First, we need the raw data. In my case, I’ll use a CSV dataset for French bank holidays. During Netlify’s build step, we’ll create all the required files that will be served by our API. In our case, we want to create one JSON file per year, which will contain the bank holidays of that year. Netlify supports a handful of languages for the build phase, I’ve used Python 3.6 (the desired Python version is specified in the file runtime.txt). My build.py file downloads CSV files, convert them in JSON and store a file per year.

We now already have a working API, that exposes transformed JSON files. You could already access these files, by using a URL like /data/2019.json. Since we’re building a REST API, we want to expose meaningful URLs. To do this, we’ll leverage Netlify’s redirect rules. You can see my redirect rules in the _redirects file. Thanks to this, the final endpoint will be /api/2019, which is far better. Since our endpoints will most likely not change, I’ve used Netlify’s custom HTTP headers to set Cache-Control HTTP headers to instruct clients to cache the received data. You can see my rules in the _headers file.

Demo for French bank holidays in 2019: https://jours-feries-france.antoine-augusti.fr/api/2019

Takeaway

We’ve used the build step of Netlify to create our desired world for our API. Now Netlify takes care of hosting it with a custom domain, providing and renewing SSL certificates. All in 35 lines of Python. Not bad.

By default Netlify will rebuild your project every time you push a commit. You could perform builds more often by using webhooks.

Sounds great? Give me a follow on Twitter or learn more about me.