Skip to content

POST requests with JSON encoded data

Travis Dent edited this page Nov 16, 2013 · 4 revisions

The format_query method normally concatenates the request parameters into a urlencoded query string, we simply replace it with a method that returns JSON. This data will get passed directly to the CURLOPT_POSTFIELDS cURL option.

Caveat: This will json_encode GET request query data as well, so you'll need to manually append an appropriately formatted string to the first argument of any GET requests.

<?php

class JSONClient extends RestClient {
    
    public function format_query($parameters, $primary=NULL, $secondary=NULL){
        return json_encode($parameters);
    }
}

$client = new JSONClient(array(
    'base_url' => "http://example.com"
));

$result = $client->post('resource', array(
    'json_data_key' => "JSON Data Value"
));
Clone this wiki locally