Problem getting json data via api using PHP
Get the solution ↓↓↓I have a code in php that gets json data using the Coinbase Pro api, but it shows an error:
"file_get_contents (https://api.pro.coinbase.com/products/BTC-USD/stats): failed to open stream: HTTP request failed! HTTP / 1.1 400 Bad Request ",
Sometimes it works for a while, then not again, but when I open the url api in the browser, it works stably, so I don't know where the problem is.
My code:
$url = "https://api.pro.coinbase.com/products/BTC-USD/stats";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);
$lastPrice = $json["last"];
$highPrice = $json["high"];
$lowPrice = $json["low"];
$openPrice = $json["open"];
Answer
Solution:
You said "sometimes it works for a while, then not again"
That means this is not a PHP or code problem but your API calls are the issue.
Their documentation does mentions that the above feed is public and doesn't requires authentication, so that part is cleared.
Now the error code they have mentioned in their documentation that 400 = Bad Request -- Invalid request format.
The only thing that remains is they are somehow throttling your requests.
Here is a part which mentions that.
"PUBLIC ENDPOINTS We throttle public endpoints by IP: 3 requests per second, up to 6 requests per second in bursts. Some endpoints may have custom rate limits."
Try to stay within those limits if possible by caching the data on your server side.
Answer
Solution:
What are the rate limits for Coinbase Pro API?
REST API
For Public Endpoints, our rate limit is 3 requests per second, up to 6 requests per second in bursts. For Private Endpoints, our rate limit is 5 requests per second, up to 10 requests per second in bursts.
Your code is ok check Here for more info
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.