Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP post to REST web service

Tags:

rest

http

post

php

xml

I'm totally new to REST web services. I have a need to post some information to a REST web service using php and use the response to give users a product(the response is the code for the product). My task : 1) HTTP method is post 2) Request body is XML 3) Headers need to have an API key ex: some-co-APIkey: 4325hlkjh 4) Response is xml and will need to be parsed. My main question is how to set the headers so that it contains the key, how to set the body, and how to get the response. I am unsure exactly where to start. I'm sure it's quite simple but since I've never seen it I'm not sure how to approach this. If someone could show me an example that'd be great. Thanks in advance for any and all help.

I'm thinking something like this;

  $url = 'webservice.somesite.com';

  $xml = '<?xml version="1.0" encoding="UTF-8"?>
      <codes sku="5555-55" />';
  $apiKey = '12345';
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);

  ## For xml, change the content-type.
  curl_setopt ($ch, CURLOPT_HTTPHEADER, $apiKey);

  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned
  if(CurlHelper::checkHttpsURL($url)) { 
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    }

  // Send to remote and return data to caller.
  $result = curl_exec($ch);
  curl_close($ch);

Does that seem about right?

like image 690
KodrKid Avatar asked Jan 20 '23 12:01

KodrKid


1 Answers

You should use cURL for this. You should read the documentation, but here is a function I wrote that will help you out. Modify it for your purposes

function curl_request($url,  $postdata = false) //single custom cURL request.
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, TRUE); 
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     

    curl_setopt($ch, CURLOPT_URL, $url);

    if ($postdata)
    {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);   
    }

    $response = curl_exec($ch);

    curl_close($ch);

    return $response;
}

As for XML, php has some great functions for parsing it. Check out simplexml.

like image 149
bgcode Avatar answered Jan 30 '23 13:01

bgcode