Using cURL to return API XML response - php

Forgive me if this is simple. My research has brought me to a halt at the moment. I am trying to use cURL to get the response of an API in XML.
This is the URL of the API: https://api.weather.gov/alerts/active/region/land
By default it returns in JSON. Which I know, I should just use the JSON response but, there is a reason I need it in XML as it will seamlessly integrate into my current code until I can rewrite it for JSON.
This is the documentation for the API. Under the API Reference tab is states I just need to change the request header to application/cap+xml. But I am not getting anything back. Just a blank white page.
https://alerts-v2.weather.gov/documentation
Here is my current code I am using to call the API but I get no response or anything. What am I missing?
<?php
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-Type: application/cap+xml;charset=utf-8';
$headers[] = 'Accept: application/cap+xml';
$userAgent = 'php';
$url = 'https://api.weather.gov/alerts/active/region/land';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPHEADER, $headers);
curl_setopt($cURL, CURLOPT_USERAGENT, $userAgent);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
$result = curl_exec($cURL);
curl_close($cURL);
?>

I've just tried your code and it works fine with atom:
$headers[] = 'Accept: application/atom+xml';
"application/cap+xml" is not available for the URLs, like you mentioned in a question though.
Per the doc https://alerts-v2.weather.gov/documentation the formats are following:
/alerts/active/region/{region} => JSON-LD (default), ATOM
/alerts/{alertId} => JSON-LD (default), CAP

Related

Strava API oAuth Process Token Exchange page can't be reached

While I am able to receive the initial Strava oAuth Code through the authorize? process on the Strava page, I am struggling with the token exchange process described here: https://developers.strava.com/docs/authentication/
Code below does only result in
Sorry, this one stays red.
The page you’re looking for doesn’t exist, but you’re not at a dead end.
Here are a few options:
Be sure you have the right url and try again
Sign up or log in at strava.com
See what the community’s been up to at Strava Stories
Search for a particular activity or club
Get a little help from Strava Support
I am quite new to the Strava API, but also directly pasting the resulting URL in the browser does result in the same page response.
$url = "https://www.strava.com/oauth/token?client_id=XXXXX&client_secret=XXXXXXXXXXXXXXXXXXXXXXXX&code=".$code."&grant_type=authorization_code";
echo "<br />".$url;
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$result = curl_exec($cURL);
curl_close($cURL);
print_r($result);
?>
Thanks in Advance for your support on this matter !
#Chris White solved it, was using POST instead of GET. Thanks for the help
echo "<br />".$url;
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$result = curl_exec($cURL);
curl_close($cURL);
print_r($result);
?>

Accessing a json api with php

I'm trying to learn how I can interface with a json api.
In the documentation they give me a curl example:
If I run this as a command it works fine, gives me my data in a json format.
I thought I was on the right track with this: PHP + curl, HTTP POST sample code?
but apparently not as I can't figure out what to do with the -H portion of this command.
curl -H "APIKey:My:ApI;key;" -H "Content-Type:.../json" "https://urlofapp.com/API/GetTransaction" -d "{ 'CustomerID':'12345','EndDate':'2018-12-31','StartDate':'2018-01-01'}" > test.json
Trying to get the result into an array that I can sum and show a total of their orders for the year.
From the link I provided above I was trying to start with this:
// set post fields
$post = [
'CustomerID' => 12345,
'StartDate' => 2018-01-01,
'EndDate' => 2018-12-31,
];
$ch = curl_init('https://urlofapp.com/API/GetTransaction');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
The -h command refers the header.
Try below code,
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://urlofapp.com/API/GetTransaction');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ 'CustomerID':'12345','EndDate':'2018-12-31','StartDate':'2018-01-01'}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Apikey: My:ApI;key;';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
I used below to convert the curl command to PHP script,
https://incarnate.github.io/curl-to-php/
Hope it would be useful.
Dealing with curl directly usually ends up being a pain. There are a number of libraries that can help making calls like that much simpler.
Here are a few:
Simple and straighforward: http://requests.ryanmccue.info/
Has everything you could ever possibly want: https://github.com/guzzle/guzzle

Twitter API token request returning gobbledygook

I'm trying to use Application Only Authentication, as described here:
https://developer.twitter.com/en/docs/basics/authentication/overview/application-only
I'm using the following PHP code to do so.
if(empty($_COOKIE['twitter_auth'])) {
require '../../social_audit_config/twitter_config.php';
$encoded_key = urlencode($api_key);
$encoded_secret = urlencode($api_secret);
$credentials = $encoded_key.":".$encoded_secret;
$encoded_credentials = base64_encode($credentials);
$request_headers = array(
'Host: api.twitter.com',
'User-Agent: BF Sharing Report',
'Authorization: Basic '.$encoded_credentials,
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
'Content-Length: 29',
'Accept-Encoding: gzip'
);
print_r($request_headers);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
$attempt_auth = curl_exec($ch);
print_r($attempt_auth);
}
It should return JSON with the token in it, but instead it returns gobbledygook, as seen in the image below:
I'm sure I'm missing some very simple step, where am I going wrong?
If I send the curl request without the headers, it returns an error in JSON format as expected, so is there something wrong with my headers?
You have few options here. Instead of setting header directly, use below
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
If you set header directly then you should use
print_r(gzdecode($attempt_auth));
See below thread as well
Decode gzipped web page retrieved via cURL in PHP
php - Get compressed contents using cURL

Posting to API with curl not working

$headers = array();
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl,CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
var_dump($result);
curl_close($curl);
I have the code above, i want to post to an api. Somehow its not working. I tried using a var_dump on the result variable. The result is:
string(117) "{"Message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}"
Any idea why its not posting to the api?
The value of the $post=
{"AmountDebit":10,"Currency":"EUR","Invoice":"testinvoice 123","Services":{"ServiceList":[{"Action":"Pay","Name":"ideal","Parameters":[{"Name":"issuer","Value":"ABNANL2A"}]}]}}
Headers:
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
If you don't specify a Content-Type header when making a POST call with Curl, it will add one in with the value application/x-www-form-urlencoded.
From the Everything Curl book:
POSTing with curl's -d option will make it include a default header that looks like Content-Type: application/x-www-form-urlencoded. That's what your typical browser will use for a plain POST.
Many receivers of POST data don't care about or check the Content-Type header.
If that header is not good enough for you, you should, of course, replace that and instead provide the correct one.
Judging by your request, I imagine you'll need to add the following to the top of your script:
$headers[] = 'Content-Type: application/json';
But depending on the exact API you're posting to, this might need to be different.
Have You installed curl before using it.
If it not install try google for Curl installation
and use my curl function for post request its 100% working-
public function curlPostJson() {
$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' .strlen(json_encode($paramdata));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paramdata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
$server_output = curl_exec($ch);
curl_close($ch);
return json_decode($server_output);
}

Stormpath Rest api PHP

can someone help me write this in the form of an httpRequest in php. I´ve tried many times and failed. I don´t know why but I simply can´t get it right.
curl -i --user $YOUR_API_KEY_ID:$YOUR_API_KEY_SECRET \
'https://api.stormpath.com/v1/tenants/current'
Any help would be greatly appreciated.
So for you to get the current tenant within PHP, you will need to let curl follow redirects as /tenant/current is a 302 redirect to the tenant for your API key
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.stormpath.com/v1/tenants/current");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = 'Authorization: Basic ' . base64_encode($YOUR_API_KEY_ID:$YOUR_API_KEY_SECRET);
$headers[] = "Accept: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
var_dump($server_output);
With this, it will return your current tenant resource.
For reference, Stormpath does have an open PHP SDK that you can use instead so you dont have to mess with cURL at all.
Stormpath PHP SDK
The SDK is installable via Composer and is in a stable release state as of 1.12.0

Categories