Thursday, December 4, 2014

A RESTful API Using Bedrock?

As I've written before, writing AJAX services in Bedrock is actually pretty trivial.  In fact, Bedrock's support of the .jroc extension which automatically sets the mime-type of the output to application/json makes creating an AJAX widget to return the current environment for example, look something like this:

<var --json $env>

Not sure how it could get any easier than that...and with a properly configured Bedrock installation, AJAX services that access information stored in MySQL tables is equally as easy.

<sqlselect "select * from customers" --define-var"customers"></sqlselect>
<var --json $customers>

I've recently started looking at using Bedrock to prototype a RESTful interface and I've been very encouraged about the simplicity here as well.  Several features of Bedrock make creating a RESTful API pretty easy.


  • Ability to interpret the environment variables (URIs), etc.
  • JSON
  • Access to POST data
  • Ability to directly set status
  • Ability to interpret and set HTTP headers


I've been studying up on creating robust, secure and compliant RESTful interfaces and think I can use Bedrock to prototype a RESTful API.  Some interesting resources I've found so far include:

REST Video Tutorial
REST API Design Rulebook
API Security Considerations

So what might a Bedrock based RESTful API look like anyway?  Consider this API:

/accounts      => returns a collection of accounts
/accounts/{id} => returns a single account's record
/books         => returns a collection of books
/books/{id}    => returns a single book record

Let's give this a shot in Bedrock...

<sink><null:uri $env.BEDROCK_URI>
<null:parts $uri.split('/')>

<hash:out>

<if $parts.[1] --eq 'accounts'>
 <if $parts.[2]>
   <sqlselect "select * from account where id = ?"
              --define-var="out"
              --bind=$parts.[2]></sqlselect>
 <else>
   <sqlselect "select * from account" --define-var="out></sqlselect>
 </if>

<elseif $parts.[1] --eq 'books'>
  <if $parts.[2]>
    <sqlselect "select * from book where id = ?"
               --define-var="out"
               --bind=$parts.[2]></sqlselect>
  <else
   <sqlselect "select * from book" --define-var="out></sqlselect>
  </if>

</if></sink><var --json $out>

Okay, this is a really simple and featureless example that doesn't consider authentication, or setting status on error, but you get the idea.  I'll be blogging about this subject as soon as I do the deep dive, but it looks promising.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.