Php make rest call

How to make a POST api call in php

Solution 1: There are multiple ways to make REST client API call: Use CURL CURL is the simplest and good way to go. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client.

How to make a POST api call in php

I have been stuck on this for 2 day now. I looked all over the internet for the answer and could not find it.

I need to make a POST request to an api to register users. This is the info I was given.

url: https://webbsite.com/api/register HEADERS . Content-Type:application/json Access-Token: randomaccesstoken Body . < 'email' =>'John.doe@gmail.com', 'firstName' => 'John', 'lastName' => 'Doe', 'password' => "mypassword1" > Response . 201 . HEADERS . Content-Type:application/json BODY . < "success": ture, "data": < "user_id": 1, "token": "randomusertoken" >> 

This is what I have so far. No matter what I do it results in an error. I feel it might have something to do with the Access-Token placement. It was hard to find an example that uses a access token. Is this the correct way to make a post request to an API in php?

$authToken = 'randomaccesstoken'; $postData = array( 'email' => 'John.doe@gmail.com', 'firstName' => 'John', 'lastName' => 'Doe', 'password' => "mypassword1" ); // Create the context for the request $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => "Authorization: \r\n". "Content-Type: application/json\r\n", 'content' => json_encode($postData) ) )); $response = file_get_contents('https://webbsite.com/api/register', FALSE, $context); if($response === FALSE) < die('Error'); >$responseData = json_decode($response, TRUE); print_r($responseData); 

From the info given, it looks like you’re just sending the header name wrong (although to be fair, Access-Token isn’t a standard header. )

$context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => "Access-Token: \r\n". "Content-Type: application/json\r\n", 'content' => json_encode($postData) ) )); 

How to make a POST api call in php, I have been stuck on this for 2 day now. I looked all over the internet for the answer and could not find it. I need to make a POST request to an api to register users. This is the info I was give Code sample’http’ => array(‘method’ => ‘POST’,’header’ => «Access-Token: \r\n».»Content-Type: application/json\r\n»,’content’ => json_encode($postData)Feedback

Читайте также:  Date get week javascript

Call a REST API in PHP

Our client had given me a REST API to which I need to make a PHP call. But as a matter of fact, the documentation given with the API is very limited, so I don’t really know how to call the service.

I’ve tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in-depth information.

Is there any decent information around how to call a REST API or some documentation about it? Because even in W3schools, they only describe the SOAP method. What are different options for making the rest of API in PHP?

You can access any REST API with PHPs cURL Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!

// Method: POST, PUT, GET etc // Data: array("param" => "value") ==> index.php?param=value function CallAPI($method, $url, $data = false) < $curl = curl_init(); switch ($method) < case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_PUT, 1); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); >// Optional Authentication: curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_USERPWD, "username:password"); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return $result; > 

If you have a url and your php supports it, you could just call file_get_contents:

$response = file_get_contents('http://example.com/path/to/api/call?param1=5'); 

if $response is JSON, use json_decode to turn it into php array:

$response = json_decode($response); 

if $response is XML, use simple_xml class:

$response = new SimpleXMLElement($response); 

Use Guzzle. It’s a «PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services». Working with Guzzle is much easier than working with cURL.

Читайте также:  Java script and php

Here’s an example from the Web site:

$client = new GuzzleHttp\Client(); $res = $client->get('https://api.github.com/user', [ 'auth' => ['user', 'pass'] ]); echo $res->getStatusCode(); // 200 echo $res->getHeader('content-type'); // 'application/json; charset=utf8' echo $res->getBody(); // json()); // Outputs the JSON decoded data 

CURL is the simplest way to go. Here is a simple call

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "THE URL TO THE SERVICE"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA); $result = curl_exec($ch); print_r($result); curl_close($ch); 

Call a REST API in PHP, The code below is something that works for me, I’m calling my own web service API, so I already know what the API takes and what it will return. It supports both GET and POST methods, so the less sensitive info goes into the URL (GET) , and the info like username and password is submitted as POST variables.

PHP REST client API call

I’m wondering, is there an easy way to perform a REST API GET call? I’ve been reading about cURL, but is that a good way to do it?

I also came across php://input but I have no idea how to use it. Does anyone have an example for me?

I don’t need advanced API client stuff, I just need to perform a GET call to a certain URL to get some JSON data that will be parsed by the client.

There are multiple ways to make REST client API call:

CURL is the simplest and good way to go. Here is a simple call

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA); $result = curl_exec($ch); print_r($result); curl_close($ch); 

It’s a «PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services». Working with Guzzle is much easier than working with cURL.

Читайте также:  Passing string argument javascript

Here’s an example from the Web site:

$client = new GuzzleHttp\Client(); $res = $client->get('https://api.github.com/user', [ 'auth' => ['user', 'pass'] ]); echo $res->getStatusCode(); // 200 echo $res->getHeader('content-type'); // 'application/json; charset=utf8' echo $res->getBody(); // json()); // Outputs the JSON decoded data 

If you have a url and your php supports it, you could just call file_get_contents:

$response = file_get_contents('http://example.com/path/to/api/call?param1=5'); 

if $response is JSON, use json_decode to turn it into php array:

$response = json_decode($response); 

If you are using Symfony there’s a great rest client bundle that even includes all of the ~100 exceptions and throws them instead of returning some meaningless error code + message.

try < $restClient = new RestClient(); $response = $restClient->get('http://www.someUrl.com'); $statusCode = $response->getStatusCode(); $content = $response->getContent(); > catch(OperationTimedOutException $e) < // do something >

Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client.

  • Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, and OPTIONS)
  • Custom Headers
  • Automatic «Smart» Parsing
  • Automatic Payload Serialization
  • Basic Auth
  • Client Side Certificate Auth
  • Request «Templates»

Send off a GET request. Get automatically parsed JSON response.

The library notices the JSON Content-Type in the response and automatically parses the response into a native PHP object.

$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D"; $response = \Httpful\Request::get($uri)->send(); echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n"; 

You can use file_get_contents if the fopen wrappers are enabled. See: http://php.net/manual/en/function.file-get-contents.php

If they are not, and you cannot fix that because your host doesn’t allow it, cURL is a good method to use.

$result = file_get_contents( $url ); 

Json — PHP REST client API call, I don’t need advanced API client stuff, I just need to perform a GET call to a certain URL to get some JSON data that will be parsed by the client. Thanks! php json api rest curl

Источник

Оцените статью