Consume REST API with PHP

1

I am starting the studies of some RESTful APIs and I have a sense of what REST is and an API. However, I'm still kind of confused about the process.

LinkedIn provides a rich RESTful API through its REST Console, for example a POST call would be (according to the API):

https://api.linkedin.com/v1/people/~/shares?format=json

Okay, now how to send this call via PHP?

    
asked by anonymous 09.11.2017 / 14:07

1 answer

3

First you must have authorization for this, you must have create an application, ask the user to authorize and then get the access_token , this is explained here and here .

I will assume that these steps are already being done. If they are not, you can follow the same principle shown below.

According to the documentation we have:

  • URL:

    https://api.linkedin.com/v1/people/~/shares?format=json
    
  • Method:

    POST
    
  • Header:

    Authorization: Bearer AQXd...
    Content-Type: application/json
    x-li-format: json
    
  • Body:

    {
      "comment": "Check out developer.linkedin.com!",
      "content": {
        "title": "LinkedIn Developers Resources",
        "description": "Leverage LinkedIn's APIs to maximize engagement",
        "submitted-url": "https://developer.linkedin.com",  
        "submitted-image-url": "https://example.com/logo.png"
      },
      "visibility": {
        "code": "anyone"
      }  
    }
    

Applying this to cURL, in the same order, we have:

$ch = curl_init();

curl_setopt_array($ch, [

    CURLOPT_URL => 'https://api.linkedin.com/v1/people/~/shares?format=json',

    CURLOPT_POST => true,

    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
        'x-li-format: json'
    ],

    CURLOPT_POSTFIELDS => json_encode([
        'coment' => 'Check out developer.linkedin.com!',
        'content' => [
            'title' => 'LinkedIn Developers Resources',
            'description' => 'Leverage LinkedIn\'s APIs to maximize engagement',
            'submitted-url' => 'https://developer.linkedin.com',
            'submitted-image-url' => 'https://example.com/logo.png'
        ],
        'visibility' => [
            'code' => 'anyone'
        ]
    ]),

    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_PROTOCOLS => CURLPROTO_HTTPS
]);

echo $resultado = curl_exec($ch);
curl_close($ch);

Remembering to insert a valid token in $token . The last two options are optional, but ideal. The RETURNTRANSFER returns the result for the variable that executes curl_exec . The PROTOCOLS limits the protocols to be used. It is also ideal to set SSL_VERIFYPEER and SSL_VERIFYHOST , but in PHP 7.1 they are already enabled by default.

    
23.11.2017 / 22:11