How to use an API in my program?

Thanks again,
This is my URL manually,
http://localhost:1367/rest-api - Copy/api-alis.php?material_code=1
But, after that, I see this URL in the browser,
http://localhost:1367/rest-api%20-%20Copy/api-alis.php?material_code=1
,However, those are the same, as far as I know.

And in my code, I tested something.
For Example, when I add echo $material_code or $url, the browser returns those,
So, I don’t know what is the problem exactly?

So, I have to share API code with you.
PS: I don’t consider security issues like sql injection, …

header("Content-Type:application/json");

if (isset($_GET[‘material_code’]) && $_GET[‘material_code’]!="") {
include(‘db.php’);
$material_code = $_GET[‘material_code’];
$query = “select material_code,importation_quantity from stock_information where material_code=$material_code”;
$result = mysqli_query($con, $query);
mysqli_query($con, “SET NAMES utf8”);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)) {
$material_code = $row[‘material_code’];
$importation_quantity = $row[‘importation_quantity’];

response($material_code, $importation_quantity);
//mysqli_close($con);
}
}else{
response(NULL, NULL, 200,“No Record Found”);
}
}else{
response(NULL, NULL, 400,“Invalid Request”);
}

function response($material_code, $importation_quantity){
$response[‘material_code’] = $material_code;
$response[‘importation_quantity’] = $importation_quantity;
$json_response = json_encode($response);
echo $json_response;
}

Very best regards,

The API code doesn’t matter yet; your curl request isn’t even seeing it. Try this:

  1. Open up your browser’s network monitor. Most browsers have this available for development: google “[my browser] show network” to see how to get to it. Make sure “preserve log” (google again) is enabled. The network monitor will show you the requests your browser is making. Preserving logs will ensure you can see what’s going on even if your browser refreshes or redirects.
  2. Go to your API URL in your browser.
  3. Tell use what you see in your network monitor.
1 Like

It DOES matter about your API code! First, the %20 is okay, that is the code for a space.

The problem is that you send out a HTML header before you are ready to send the Json results.
There are several issues you need to change in the API code to fix this. First, you can not send
the header before the data is ready. It must be sent just before the Json is echo’d.
But, you must remember, you can only send the header once. Your code processes all of the rows found from a query which would be multiple times. You can NOT do this! One header per results, multiple headers will mess with the browser’s render of the data. If you need more than one row of data to be sent, you must build the Json results fully and send the entire list of rows in the Json array.
So, build your Json response in full including all rows of needed data. Then, send the header ONCE and follow it with the Json response data. Not multiple headers.
Of course, then you would have to alter your reading page that accesses the API to decode all of the rows that are sent.
Hope this make sense to you. Sending multiple headers is the cause of the problem. They are decoded in the browser as redirects, one after another for each row of data sent out. Good luck with the changes!

1 Like

I looked through the API code OP posted, but I only see the one header - the Content-Type one. What did I miss?

1 Like

He sends the headers, then continually calls a routine that creates Json and sends it out over and out. It should not be done that way. He should create the FULL json and send that right after the header is sent out. Each time you send data thru an echo, it sends the browser a header. Nice the false redirect.

1 Like

He’s seeing a 301 response in the browser; that corresponds to a 301 header being sent by the API. PHP won’t send one of those by accident; you have to explicitly call the header() function to do it. Which bit of his code is doing that?

1 Like

Well, the API code does send a header out using the header() function. But, the echo code is called many times and each sends text to the browser. Quite often that can cause PHP to send out another header. I suggested that he create one json result and send it as you should. Not send many different ones in a loop.
If you know how he should fix this, show him some code.

1 Like

I don’t, I’m still trying to get my head round it. I’d like to see the network traffic just to confirm what’s happening. Thanks for clarifying.

1 Like

Well, this full page:
<? PHP>echo "test line"; < /PHP>
sends a header out to the browser. The setting of a header using the header() function sends it in preparation for special output as needed. Be it a PDF file, an OBJ created from PHP code or just a simple Json created from calculations or database data.
For each different header, the data sent is handled immediately after sending the header. It is sent to the browser in different ways. Json is normally sent out right after sending the header. Header(); echo json;
This was done in the code he posted. But, then, several other json’s were sent. Depending on the server and the browser, this can cause the header to be resent. It might be making the second json into an HTML item and therefore the second header would be created. This would cause a redirection to a second header, but, would leave the URL in the browser the same. ( Headers sent from the same page do not change the URL listed in the browser. ) Hope that helps explain.

1 Like

Thanks @ErnieAlex.

@mohamad, what happens if you replace your API file with this?

<?php
header("Content-Type:application/json");
echo '[{"material_code":"1","importation_quantity":"125"}]';

That’s a minimal JSON return and will confirm Ernie’s suggestion.

1 Like

Good idea! Thanks for suggesting that!

1 Like

Thanks for your time,
I did what you said, I see the following image:


Thanks again

I tested your latest code, the browser shows the previous result.
D:\wamp64\www\rest-api- copy\fetch.php:17:null

But when I enter URL manually in the browser, it returns
[{“material_code”:“1”,“importation_quantity”:“125”}]

Maybe, it is better to rewrite API code based on my requirement. Then I can share my files with you.
or you think that, it might be solved?
Again thank you very much for your valuable time and consideration.

If you have the opportunity, then yes you should rewrite that API. There are a lot of problems with it, not least the fact that it’s outputting invalid JSON. You should also remove the spaces from the API path if possible.

That said, it looks like you still have the same problem with the minimal response I gave you earlier. You say fetch.php currently prints null; that’s the output of json_encode($response) right? What happens if you just echo $response?

1 Like

Thanks for getting back to me.
when I add echo $response; the browser can show this:
[{“material_code”:“1”,“importation_quantity”:“125”}]
So, is it possible to fix it or I try from the first?
Thanks in advance.

Ok. That looks like your PHP install is failing to decode the json, which is mad. Just for sanity’s sake, so we can see where you are right now:

Your API file currently looks like:

<?php
header("Content-Type:application/json");
echo '[{"material_code":"1","importation_quantity":"125"}]';

Can you change your fetch.php file to look like:

if (isset($_POST['material-code']) && $_POST['material-code']!="") { 
    $material_code = $_POST['material-code']; 
    $url = "http://localhost:1367/rest-api - Copy/api-alis.php?material_code=".$material_code;

    $client = curl_init($url); 
    curl_setopt($client,CURLOPT_RETURNTRANSFER,true); 
    $response = curl_exec($client); 
    $result = json_decode($response);

    echo $response . "\n";
    var_dump($response);
    echo json_last_error_msg() . "\n";

    foreach ($result as $results) {
        print "{$results->material_code} {$results->importation_quantity} \n";
    }
}

and let us know what you see?

1 Like

Thank you very much,
I tried with your new instruction, and the result is something like this:
[{“material_code”:“1”,“importation_quantity”:“125”}]

D:\wamp64\www\rest-api2\fetch.php:16:string ‘[{“material_code”:“1”,“importation_quantity”:“125”}]’ (length=52)

No error 1 125

Looking forward to your valuable comments.

Well, now you can add the json_encode() around it in the api page. Add json_decode to the main page and retest again. You can not just print the json_decode part, you would var_dump it.

Then, if that test works, you can add back in your database query to the API and be all set…

1 Like

Thank you very much, I tested it, it returns something like that:
{“material_code”:“1”,“importation_quantity”:“125”}{“material_code”:“1”,“importation_quantity”:“150”}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:“250”}{“material_code”:“1”,“importation_quantity”:“500”}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:“2000”}{“material_code”:“1”,“importation_quantity”:""}

D:\wamp64\www\rest-api2\fetch.php:16:string ‘{“material_code”:“1”,“importation_quantity”:“125”}{“material_code”:“1”,“importation_quantity”:“150”}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:“250”}{“material_code”:“1”,“importation_quantity”:“500”}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,"importat’… (length=580)

Syntax error

( ! ) Warning: Invalid argument supplied for foreach() in D:\wamp64\www\rest-api2\fetch.php on line 18

It looks, it returns correct results, but what the problem with the warning(foreach)?

Sponsor our Newsletter | Privacy Policy | Terms of Service