Consume API REST with PHP

Asked

Viewed 9,213 times

1

I’m starting studies of some Restful Apis and have a sense of what REST is and an API. However, I’m still a little (very) confused about the process.

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

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

Ok cool, now how to send this call via PHP?

  • 1

    You can use Curl for sending, or use a lib like Guzzle!

  • Pow se manjar de Curl would be nice to add a reply... I’ll even insert the tag Curl...

1 answer

5


First you must have authorization for this, you must have create an application, request the user to authorize and then get the access_token, that’s explained here and here.

I will assume that these steps are already being done. If they are not, you can follow the same principle as 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 that you must enter a valid token, no $token. The last two options are optional, but ideal. The RETURNTRANSFER returns the result for the variable that executes the curl_exec. Already the PROTOCOLS limits the protocols to be used. It is also ideal to define the SSL_VERIFYPEER and the SSL_VERIFYHOST, but in PHP 7.1 they are already enabled by default.

Browser other questions tagged

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