Is There a 'Kirby-Way' to Send a POST Request?

Hi all!

I am putting together a controller, where I need to access an external, third-party API. The controller needs to POST some data to a specific URL, and then will get a response.

I know that there are built-in ways in PHP to make a POST request both with curl and without curl, but I wondered whether there is a more ‘Kirby-like’ way of doing this.

I’ve had a look through the docs on the $request object, but the purpose there seems to be to inspect the current request, rather than create a new one. Is there a class somewhere in the Kirby framework that allows us to send a new, arbitrary request?

The Remote class is your friend

In particular Remote::request(): https://getkirby.com/docs/reference/@/http/remote/request

Example:

$url = 'http:://your-api-url';
$data = [];
options = [
    'headers' => [
         'Authorization: Bearer ' . trim(option('mykey')),
         'Content-Type: application/json'
    ],
    'method'  => 'POST',
    'data'    => json_encode($data)
 ];
$response = Remote::request($url, $options);
2 Likes

Thank you, @texnixe! I knew there was something!

@texnixe I just thought I’d update the code example here, with a little example of my own - for future reference, in case anyone finds it useful. I ran into an issue with the code above, because it shows how to post json-formatted data - and I needed to access an API that only accepted “normal” (non-json) data.

So, if you don’t want to post JSON data, you can do a standard post request like this:

$url = 'http:://your-api-url';
$data = [ 'foo' => 'bar'];
$options = [
    'method'  => 'POST',
    'data'    => http_build_query($data)
 ];
$response = Remote::request($url, $options);