Creating an API from local data

Let’s say I have a projects.json file in my local data folder that I’m using to generate a list of projects.

My question is simple: is there an easy way to also serve that file as raw json, in order to build a simple API?

Typically no. The /data directory that holds your json files is parallel to your /source directory. When Middleman creates the site it uses the combination of /data with /source to create the third directory that is parallel with other two called /build. This build directory does not contain a copy of /data within it. Typically it is the output of the /build directory that is deployed to a web server.

However there is nothing that stops you from writing a custom extension that using the after_build callback could copy your /data directory into /build that once deployed another webserver could interact with as a basic API.

See http://middlemanapp.com/advanced/custom/ for more information. I don’t know of one off the top of my head but the extensions directory may have an example of an extension using the build callback.

Thanks, I’ll have to look into that.

I had to something like that recently, although my data was in yaml, not json, what I ended up doing was I put a projects.json.erb file in source/ and inside that file, I just wrote this:
<%= data.games.to_json %>
I was able then to load that json file on http://localhost:4567/projects.json

2 Likes

Brilliant. Why didn’t I think of that :slight_smile: