Search code examples
phpapi

API code error 400 - when trying to call API in php


I'm trying to call an api in php however it comes up with error 400 even though if i try to do the same api call in python it works fine.

This is the php code I'm trying to execute the echoes are the just to see what is going on:

if (isset($_POST['stock']))
{
    $ticker = $_POST['stock'];
    echo $ticker;
    $json = file_get_contents($url);
    echo $json;
    $data = json_decode($json,true);
    echo $data;
    print_r($ticker." price: ".$data);  
}

the url is:

$url = "https://api.twelvedata.com/price?symbol=".$ticker."&apikey=".$TDKEY;

with ticker and tdkey being variables, I think this is correct there's nothing I can see that's wrong here.

and the output is:

AAPL{"code":400,"message":"There is an error in the query. Please check your query and try again. If you're unable to resolve it contact our support at https://twelvedata.com/contact/customer","status":"error"}ArrayAAPL price: Array

Solution

  • Where are you setting the URL? Your code shows that the ticker variable is only set in the if statement, but it is never passed to the URL variable - Therefore $url = "https://api.twelvedata.com/price?symbol=".$ticker."&apikey=".$TDKEY; cannot be valid, as ticker is seemingly not set at the time of URL being intialised

    Additionally, using print_r($ticker) is also going to throw an error, it's a variable, not an array

    Your code needs to become

    if (isset($_POST['stock']))
    {
        $ticker = $_POST['stock'];
        $url = "https://api.twelvedata.com/price?symbol=".$ticker."&apikey=".$TDKEY;
        $json = file_get_contents($url);
        $data = json_decode($json,true);
        echo $ticker." price: ";
        print_r($data);  
    }
    else
    {
        throw Exception("Ticker is not set");
    }