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

Asked

Viewed 29,844 times

4

I consider it quite simple to execute a GET request, normally I 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 of response, use the json_decode() and work that data.

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

I wish I knew the best way to do it.

If possible, I did not intend to use Curl for I have come across restrictions where I could not make use of it...

  • You use Zend Framework?

  • I didn’t want to use any framework...

2 answers

14


I used the following code snippet to request POST 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
  • @William That’s what you need?

  • I believe so, @fymoribe. I’ll leave the question open for now because I’ll only be able to test again in the api tomorrow. But thanks.

5

There are several ways to do this with PHP, the most common way is by using 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 Curl documentation to explore all available functions and options for customizing requests: http://php.net/manual/en/book.curl.php

Although Curl is easy to use, there are libraries made in PHP, such as Guzzle, which provide an object-oriented abstraction layer on top of Curl, making 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();

By the way, Guzzle also has great documentation: http://guzzlephp.org/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.