I need to get a PIN code through an API but I can’t get the Body of an End-Point response.
The process is very simple and requires no authentication.
Just send the email in the MAILTO field and the webservice returns the pin, or says that the email was not found. In my case below, I just want to receive the Json. But I can’t do that.
However, when I test the endpoint in Postman, it works perfectly. But I can’t when I try in PHP, even getting the CURL generated by Postman itself.
Here’s the PHP code I’m using.
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api-dev.meucliente.app.br/api/Login/sistema/[email protected]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
$esposta = curl_exec($curl);
curl_close($curl);
header('Content-Type: application/json');
var_dump($esposta);
?>
The above script returns the following result:
string(123) "HTTP/1.1 404 Not Found
Date: Thu, 24 Nov 2022 14:28:51 GMT
Content-Length: 0
Connection: keep-alive
Server: Kestrel
When I test the same end-point in Postman, the return is correct:
[
{
"Mensagem": "Email não foi encontrado!!",
"InnerException": null
}
]
I will be very grateful to whoever helps me.
3
Answers
I found the solution to the problem. In PHP version 8.0.22, to get the BODY in a CURL request in the POST model, I also need to send the BODY, even if it is empty.
Here is the script that worked:
You did not include your Postman settings and the problem is there. Actually the problem is in your cURL request that does not mimic the Postman request. By default, cURL does
GET
request but the API you talking to apparently expectsPOST
type of request and simply drops all request to that endpoint that do not meet that expectation. If you change your Postman method type toGET
and try to do the request then you would get no JSON back as well, same you faced with your PHP code.So if that’s the only problem you have, you need to also do
POST
request and to do that just add:to your code and should be good:
which would return expected data:
BTW: the line
is incorrect. You are not outputting plain JSON but just string (as per
var_dump()
) so you should either have it removed, or removecurl_setopt($curl, CURLOPT_HEADER, true);
and replacevar_dump()
with plainecho
. Or just replaceheader()
withecho '<pre>';
if you test this in browser.If you get the url corrected, your code should work just fine.
That is if the request should be a GET which is likely.
What you referred to as your response, is not a response.
It is the response header and you got that only because you have this option:
The request failed.
Take a look at the first line of the response header.
It returned HTTP status of
404 Not Found
This is not a valid URL:
https://api-dev.meucliente.app.br/
It does not work in postman either.