Skip to main content

Basic Agent-to-Internet Communications

Recommended Code Flow For Making HTTP Requests

In addition to receiving HTTP requests — see Internet-to-Agent Communications — agents can also make HTTP requests using any of the common HTTP request verbs: GET, POST, PUT, DELETE etc. The imp API also provides mechanisms for making such requests synchronously (wait for the response) or asynchronously (deal with the response as and when it arrives).

The generic way to create an HTTP request is with the imp API method http.request(), however the API also includes convenience methods for specific HTTP methods: http.get(), http.httpdelete(), http.post() and http.put(). In each case, the URL passed as a parameter must start with "http:" or "https:" — ie. it must include the colon.

All of these methods generate an imp API httprequest object but do not send it. This is achieved with the httprequest methods httprequest.sendasync() and httprequest.sendsync(). The latter returns a table containing the information returned by the remote service, or an error. The former passes the same table (or error) to the callback function it registers.

However the httpresponse object is acquired, it is used to acknowledge receipt by calling its httpresponse.send() method.

Sample Code

The following code snippets show the creation and transmission of a simple HTTP GET request. The first snippet sends the request asynchronously: the imp does not block; the nominated callback is processed when a response is received. The second snippet sends the same request synchronously: the imp will block until a response is received.

Use either snippet according to which is most appropriate for your application. The code uses the GET method, but the imp API calls for other HTTP methods — pre-defined or custom — are created with appropriate methods, and then send and parsed the same way. Which you use will be governed by the service your agent is contacting. However that service operates, this agent code allows you to send and receive information from it.

API Properties Used

API Methods Used

Further Reading