REST dummy server

I must admit; even for the easiest problems I try google first. Those people at stackoverflow seem to have a solution for everything, right?

So I wanted a dummy rest server that would just serve static JSON. I wanted to take my development home, on my local machine. So I thought I’d just save some output from our API to a file, and then put it in a dummy server. This was probably too easy, Google came up with solutions that were more complicated. So for the lazyweb, I will share my solution with you. You’ll be al set in a few minutes!

I assume you already have a VirtualBox running with your LAMP stack, or maybe xampp, wamp or whatever. I used Apache for my solution.

Create a virtualhost

I must say I had some issues with this new Apache 2.4 thing, not accepting my .htaccess rewrite rules. So here is my virtual host config, so you can copy paste, and adjust it to your needs.

.htaccess

I didn’t put the rewrite rules in the VirtualHost config, but added that to my .htaccess in the documentRoot like this:

index.php

The php parses the requests, and loads the json files from disc. Nothing more to it. You could adjust it a bit and maybe mock some auth tokens as well, but for me that wasn’t required in this phase.

As you can see, the path if being converted to a filename by replacing the slashes with dashes. So now you can easily create json files for every request.

http://api-server.local/node is read from node.json
http://api-server.local/node/11 is read from node_11.json
http://api-server.local/node/11/statistics is read from node_11_statistics.json

You get the picture, right? Now, wasn’t that easy?

Alternatives

Of course there are way smarter, probably better alternatives. I tried the JSON Server, which is really cool, because it can handle the requests by a simple database which you define in json as well. But my problem was that not all our resources did have primary keys (id’s), so I didn’t know how it should handle that. Also you would have to JSON code the (piece) of database, while in my case I could just dump some requests to file.

Also, our API required more levels (e.g. /node/11/stats/12) and I didn’t want to spend a lot of time figuring out how this could be done with JSON Server.

Mock-server also looked pretty awesome, but it would probably also take me too much time to figure out how to install and configure the thing.

I kind of stopped my journey looking for dummy rests servers there, because I then realized I could build one myself pretty easy.

And now you can too, without even having to think about it. That’s what I wanted too.

Leave a Reply

Your email address will not be published. Required fields are marked *