Skip to main content

http.onrequest(callback)

Registers a function to be executed on receipt of an incoming HTTP request

Availability

Agent

Parameters

Name Type Description
callback Function An HTTP request handler callback

Returns

Nothing

Description

This method registers a handler function which will be called whenever an HTTP request is sent to the agent’s external URL. In the Electric Imp IDE, impCentral™, this URL can be found under ‘Device Settings’ or at the head of the agent code panel. It can also be obtained by the agent itself using the API method http.agenturl().

The function passed into the callback parameter has the following parameters of its own:

Parameter Type Description
request Table The incoming HTTP request decoded into key-value pairs
response An httpresponse object An automatically generated HTTP response for replying to the source of the request

The table passed into request contains the components of the request made to the agent. The table has the following structure:

Key Type Description
method String The HTTP method (verb), eg. "GET", "PUT", "POST"
path String The HTTP path, minus the agent ID
query Table A table containing all of the query parameters (if any)
headers Table A table containing all of the request headers
body String The request body, if any

For example, if the agent’s URL is:

https://agent.electricimp.com/a1b2c3d4e5f6

and the following request is made:

https://agent.electricimp.com/a1b2c3d4e5f6/api/light?state=on&color=255,255,0

then the path will be /api/light and the query will be:

{ "state" : "on",
  "color" : "255,255,0" }

For ease of access from Squirrel, all headers in the headers table are presented in lower case, even if they were received in upper case. According to the RFC2616 specification, headers are case-insensitive.

The callback’s second parameter, response, will be a suitably configured httpresponse object that is provided automatically — it should be used to respond to the request.

When writing a handler, please be aware that the size of the request’s body field can be no bigger than 512KB. If the body field is larger than this, the request as a whole will be rejected by the server and so not relayed to your agent and its HTTP request handler.

Each agent only has one handler; setting a new one removes any previously assigned handler. To remove the handler’s registration entirely, pass null as the method’s parameter:

http.onrequest(null);

Example Code

The following example allows you to control an LED from your web browser.