How to send a POST request to a REST API in PHP?

3

I consider it quite simple to execute a GET request, I usually use:

    //$serverurl contem a url da api para a função desejada

    try {
        $cursos = file_get_contents($serverurl);
    } catch (Exception $e) {

    }

After getting a json response, I use json_decode() and work on that data.

But I'm having difficulty executing a POST request, where I need to pass some parameters to the webservice.

I would like to know the best way to do this.

If possible, I did not intend to use curl because I already encountered restrictions where I could not use it ...

    
asked by anonymous 17.12.2013 / 15:22

2 answers

14

I used the following code snippet to do POST request for API:

            $servidor = $_POST['servidor'];

            // Parametros da requisição
            $content = http_build_query(array(
                'txtXML' => $_POST['txtXML']
            ));

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'POST',                    
                    'header' => "Connection: close\r\n".
                                "Content-type: application/x-www-form-urlencoded\r\n".
                                "Content-Length: ".strlen($content)."\r\n",
                    'content' => $content                               
                )
            ));
            // Realize comunicação com o servidor
            $contents = file_get_contents($servidor, null, $context);            
            $resposta = json_decode($contents);  //Parser da resposta Json
    
17.12.2013 / 15:48
5

There are several ways to do this with PHP, the most common way is to use the curl library:

$url  = 'http://server.com';
$data = ['key' => 'value'];
$ch   = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$result = curl_exec($ch);

curl_close($ch);

Curl provides a complete and flexible HTTP client. Check the curl documentation to explore all available functions and options for customizing requests: link

Although the curl is easy to use, there are libraries made in PHP, such as Guzzle, that provide an object-oriented abstraction layer on top of the curl, making the code much more readable and elegant:

use Guzzle\Http\Client;

$client   = new Client('http://server.com/');
$request  = $client->post('users', $headers, $data);
$response = $request->send();

Incidentally, Guzzle also has great documentation: link

    
29.01.2014 / 13:20