This notebook demonstrates the HTTP extension which introduces the %server
, %server.static
and %server.route
commands to implement a HTTP server and handle API requests.
In [1]:
%extension http
The %server
command can be used to start a server on a specified port, and it can also be used to stop it. The server is accessible via any process on the local machine.
In [2]:
%server start -p 8081
Static content can be declared inline within the cell. The name serves as the key for the content, and can be used to update it subsequently. It is also used in creating the URL that serves the content.
In [3]:
%%server.static add --name foo --mime text/plain
Hello World!
Static content can also be associated with the current value of a variable previously defined in the notebook. For example, the next cell defines a variable named jsondata
to the result of parsing a JSON literal, and the subsequent cell exposes it as static content with the name json
In [4]:
%%json --name=jsondata
{
"abc": 123
}
In [5]:
%server.static add --name json --mime application/json --data jsondata
You can declare request handlers as functions and then expose them as route handlers. The next cell defines a function named helloHandler
that is then exposed as the /hello
endpoint (by default for the GET HTTP method).
The following cell uses the %request
command also provided by the HTTP extension to invoke that endpoint. While the example shows the notebook invoking the endpoint also published by the notebook, in reality some other client application could be the one invoking the endpoint.
In [6]:
function helloHandler(req, res) {
res.send('Hello World!');
res.end();
}
In [7]:
%%server.route add /hello --handler helloHandler
In [8]:
%%request
GET http://localhost:8081/hello
You can also write the script defining the request handler inline when declaring the route. In this case, you do not write the signature of the function. The code you write becomes the body of a generated handler, and the request and response objects exist within scope of the function body.
In [9]:
%%server.route add /echo --method POST
response.json(request.body);
response.end();
In [10]:
%%request
POST http://localhost:8081/echo
Content-Type: application/json
{
"xyz": "xyz"
}
Routes are dynamic. You can remove existing routes, or replace the implementation of an existing route.
In [11]:
%%server.route remove /echo
In [12]:
%%request
POST http://localhost:8081/xyz
In [13]:
%server stop
In [ ]: