Craft 3 version: There won't be a Craft 3 port of this plugin, as the Craft Fetch plugin, available for Craft 3, provides a similar list of features.
Create and send HTTP requests from templates and retrieve the response, in JSON or plain text.
Once the plugin has been installed, you may access it through the "craft.httpReq" variable in the templates. Here is an overview of the available methods:
Sends a GET request to the specified endpoint.
Parameters:
Example:
craft.httpReq.get('http://domain.com/api/test', { "lang" : "fr" }, false)
This code will try to make a GET request to http://domain.com/api/test?lang=fr without trying to get the response from cache.
{
"statusCode": 200,
"body": (parsed JSON object),
"erro": "Contains the error message, if any"
}
In order to insert custom headers in the request, use the additional options array. Example:
craft.httpReq.get('http://domain.com/api/test', { "lang" : "fr" }, false, {
headers: {
"X-Custom-Header": "foo"
}
})
Sends a POST request to the specified endpoint. POST requests are never fetched from cache.
Parameters:
Example:
craft.httpReq.post('http://domain.com/api/test', { "fname" : "John", "lname" : "Doe" }, { "cv": (UploadFile) })
This code will try to make a POST request to http://domain.com/api/test with the following parameters encoded using multipart/form-data: fname, lname, cv. The value for the CV parameter is the content of the file.
Return value:
{
"statusCode": 200,
"body": (parsed JSON object),
"erro": "Contains the error message, if any"
}
To be called before a request is being done. It can be used to specify the number of seconds during which the cache should be active.
Parameters:
Example:
craft.httpReq.setCacheTtl(60)
This will define a cache validity time of 1 minute for all further requests.
Helper method to safely retrieve a list of parameters (GET or POST) from the current Craft request.
Parameters:
Example:
craft.httpReq.getParams(['fname','lname'])
Return value:
{ "fname": "John", "lname": "Doe" }
Helper method to retrieve a list of uploaded files from the current Craft request.
Parameters:
Example:
craft.httpReq.getFiles(['cv'])
Return value:
{ "cv": (UploadFile) }
We use Craft's caching system to store the responses. The TTL is of 1 hour per default, but this value can be changed using the setCacheTtl
method.
As this plugin was mainly created with the idea to query REST API, the session handling is not really at its best. We create a single CookieJar in memory that remains during the whole Craft request.