Preskoči na glavno vsebino

Making a minimal web-application server #1

I expect a minimal web-application server to do two things:

  • serve semi dynamic html pages
  • provide an API interface to web-based client 

Very simple HTTP-based API

You can create your API-s in plethora of ways, but I mostly used a very simple strpc "standard" to do my API-s for the last 14 years. It's very easy to create and serve an API on the server side and it's very easy to call such API. Any programming language, or a bash shell can do it without any special libraries. I called it strpc (SoTinyRPC) back then.

In short, a HTTP POST request to url like this:
www.example.com/API?_r=util&_m=add

with url-encoded arguments in a POST payload:
a=100&b=11

... would be an example of strpc call.

_r - defines resource
_m - defines method
_f - (optional) would define response format (json, csv, html, ...)
_x - (optional) would define explore mode (api self-documents itself)

You can make a strpc call from your shell using Curl command, for example:
curl -k \
-u $TOKEN:x \
-d "id=12&full_name=Jim&personal_tax_id=12345678" \
"https://www.example.com/API?_r=operator&_m=update"

First implementation

I wanted to define resources and methods of an API as naturally as possible. I used an ordinary context to define a resource. And created a webfn function, that defines our API methods. It uses Rye-s validation dialect do determine the validation rules of the method's arguments. Result of a webfn is encoded in JSON and returned to the client. If validation error happens, it is also returned as JSON to the client. 
 
I needed two more functions to route to the right resource and select and call the right method.
 
Our application framework consists of just 5 functions so far, and does selection of resources and methods, JSON encoding, input validation and basic error handling .
 
Below is the code of a web-server, our "web-framework" and an example resource all on one screenshot. :)
 
 

 
You can get this example source code on github.

We will test and refine this in our next blogpost.

Komentarji