20150420

Cookie Based API login using Guzzle

We've all used curl to consume external services - scraping, APIs, etc. We know that curl is awesome, but there is that feeling that you should be doing this in a more abstract way, or using something not too hardcore.

Yesterday, I had to connect to an external API using cookie based authentication. I initially thought of doing it with curl, but I remembered Guzzle, and wanted to give it a try.

Hello Guzzle
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. 
In pseudocode:
  • create a guzzle client
  • create a cookie 
  • login and update that cookie
  • use that cookie for next requests
Here is an example:

1:  // Create a Client   
2:  $client = new \GuzzleHttp\Client\Client([  
3:    'base_url' => 'http://someserver.com',  
4:    'defaults' => [  
5:      'headers' => [  
6:        'Accept' => 'application/json'  
7:      ]  
8:    ]  
9:  ]);  
10:    
11:  // Create a new cookie  
12:  $cookieJar = new \GuzzleHttp\Cookie\CookieJar();  
13:    
14:  // Send a post  
15:  $request = $client->createRequest('POST', '/api/login', [  
16:    'cookies' => $cookieJar,  
17:    'body' => [  
18:      'UserName' => 'USERNAME',  
19:      'Password' => 'PASSWORD',  
20:    
21:    ]  
22:  ]);  
23:    
24:  // ....  
25:    
26:  // Reuse the cookie for next requests  
27:  $response = $client->get('/api/user', [  
28:    'cookies' => $cookieJar  
29:  ]);  

You can store the cookie in a shared session so that you don't need to login each time you do a request.

Links:

  • Fetching a URL with Cookies using curl: http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm

No hay comentarios.:

Publicar un comentario