Using Docker to Stub API Calls

Mar 21, 2017   #docker  #sinatra  #testing  #mock 

At my day job I work on a lot of APIs. I build APIs, I talk to APIs. It’s API city for me.

Most of the time, I’ll communicate with a development API as part of my testing. This works great in most cases, but occassionally I want to have the API I’m interacting with return specific responses and HTTP status codes. This can be tedious/impossible when working with a real API, even in a development environment.

Mock Servers

For this reason, I built the sinatra-mock project. Sinatra Mock is a Docker-based API that makes it simple to stub out API methods. You just create a single page Sinatra app that has the endpoints you want to mock. I’ve even provided a shell script that just requires the file name, the port, and a Docker container name.

A shortcoming with this project is that you can’t do domain-based (i.e. pointing to mydomain.com) API testing. Internally our APIs are all assigned a unique port for each API, so for me it’s simple. Even when I must point to an external API, I can just change my development properties file so that it includes a unique port. If you can’t use unique port mapping, then this project may not be for you.

Example

Here’s a simple Hello World example on port 8080.

  # hello_world.rb
  get '/*', provides: 'json' do
    json salutation: 'Hello World!'
  end

  get '/*' do
    'Hello World!'
  end
./mock-server -p 8080 -f hello_world.rb -n hello-world

With this example, I set it up so that calling this API on any endpoint at port 8080 will return Hello World!. If you ask for JSON, it will return {"salutation": "Hello World!"}.

Conclusion

Like I said, it’s pretty simple, but I use it all the time! Since it’s a Sinatra app you don’t have to use it only for APIs. I’ve also used it to simulate pulling down an HTML page to parse data.

It shouldn’t replace unit testing, but it is helpful when integrating with other services. Enjoy!