I always dreamt about an API powered website for armoredcode community. I do think that every website should publish some sort of API to use services.
That’s why APIs for armoredcode are online.
I started last week hanging out on this project.
Sinatra is the standard de facto choice for
building an API with ruby but, which framework to be used on top of this? Is
there out there something I can use to quickstart my project?
The answer is yes, it’s called grape. Grape is a micro-framework built on top of Rack that provides a DSL to write APIs.
So let’s start the my first coding run. The goal is to implement an API to provide gengiscan as SaaS for people don’t want to install and run my gem on their machine.
Layout
Source code layout is the standard Sinatra application. Some service files on the root dir, the magic app.rb file, public, tmp and spec folders.
Gemfile is very basic. We will use gengiscan starting from version 0.40 that introduces better error checking and we will use grape. We will make TDD so we are going to use rspec and rack-test to write tests for our API.
1 2 3 4 5 6 7 8 9 | |
Rakefile is in place just to provide rspec tasks. No great deals in this.
1 2 3 4 5 6 7 | |
TDD, let’s do testing
Grape page at github is great in giving help on using rspec.
1 2 | |
As a behavior I want a gengiscan api url that it will be called using POST HTTP method and the caller must give an host parameter and an optional port in the HTTP POST request.
Of course, there is also an hello world.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | |
I can improve my tests more mocking up a webserver, with plenty of response using webmock I used for gengiscan but it will be a further enhancement.
The API source code
You can imagine a complex ruby application that makes all of these tests going green. You’re wrong. Just 26 lines of code including empty lines thanks to grape.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
With the prefix and version keywords I fixed that all the following url calls start at ‘/api/v1’.
Saying hello to the world is very easy as you may expect from a rack powered application.
1 2 3 | |
1 2 | |
Handling gengiscan is easy as well. You’ve just to take care about parameter in the request. I used a namespace since I want a clear source code if I’ll add (and I’ll do) a get handler explaining how to use the gengiscan API.
1 2 | |
1 2 | |
That’s all. You can POST your requests to gengiscan api specifying the host to fingerpring in the host parameter and you’ve got an optional port parameter if the server accept connection on non standard HTTP 80 port.
As far as today, making requests on HTTP is hardcoded so you can’t fingerprint an HTTPS powered server even mimic a connection on port 443.
1 2 | |
Enjoy it.