No response message after calling an API - flutter

Future<EventObject> addStudentToSubject(String studentCode, String subjectid) async {
try {
final encoding = APIConstants.OCTET_STREAM_ENCODING;
final response = await http.post('${APIConstants.API_BASE_LIVE_URL}/controller_educator/add_student_to_subject.php',
headers: {
'Accept': 'application/json',
},
body: {
'stud_code': studentCode,
'subj_id': subjectid
},
encoding: Encoding.getByName(encoding)
);
print("YAWA" + response.body);
} catch (Exception) {
return EventObject();
}
}
Is there something wrong with my code why i theres no response message??
Logcat just says "I/flutter ( 5013): YAWA"
Don't know what i'm missing.

I do not believe your API does not work in Postman. Can you indicate what status code did you get in Postman?
The problem in your code is your not checking the status code response of your API. The POST request you have called has probably had an empty body. Some POST request only returns the status code.
You should always check the status code of the API. If it returns 200 means your API has processed your request successfully.
final encoding = APIConstants.OCTET_STREAM_ENCODING;
final response = await http.post('${APIConstants.API_BASE_LIVE_URL}/controller_educator/add_student_to_subject.php',
headers: {
'Accept': 'application/json',
},
body: {
'stud_code': studentCode,
'subj_id': subjectid
},
encoding: Encoding.getByName(encoding)
);
print(${response.statusCode});
if (response.statusCode == 200) {
String data = response.body;
print(data);
} else {
print(response.statusCode);
}

Related

Getting empty response body from a http post request to an api

This is my code. The goal is to get the link with file id.
// body parameter
Map<String, dynamic> body = {'file_id': 123};
String jsonBody = json.encode(body);
// response request
var download_response = await http.post(
Uri.parse('https://api.opensubtitles.com/api/v1/download'),
headers: {
'Content-Type': 'application/json',
'Api-Key': 'yCTZwGASncUthpMkMkbQDjcUdrrM2r8v'
},
body: jsonBody,
);
// print
debugPrint(download_response.body.toString());
I think I should be getting a JSON data response which I'm getting properly with postman but in flutter I'm getting empty response.
Things I tried:
encoding the body with jsonencode
correct syntax formatting
writing the body in plain json string
var headers = {
'Api-Key': 'yCTZwGASncUthpMkMkbQDjcUdrrM2r8v',
'Content-Type': 'application/json'
};
var request = http.MultipartRequest('POST', Uri.parse('https://api.opensubtitles.com/api/v1/download'));
request.fields.addAll({
'file_id': '123'
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}

Future Call return API key invalid error UNAUTHORIZED

I'm trying to access an api endpoint using a Future and it constantly returns
{"code":"UNAUTHORIZED","message":"Invalid API Key","timestamp":"2022-03-19T16:57:02.300792Z","trackingId":"4E98D1A6:9539_0A5D03B2:01BB_62360B5E_7DAF37:3959"}
I know the reason why it failed is obvious in the error message but I don't know where where my call is going wrong.
I'm using the correct API key
Future<void> getThingsToDo() async {
var headers = {
'exp-api-key': '*******-**My-API*-*KEY-************',
'Accept-Language': 'en-US',
'Accept': 'application/json;version=2.0',
};
try {
var url = Uri.parse(
'https://api.sandbox.viator.com/partner/products/5010SYDNEY');
var response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
var jsonData = json.decode(response.body);
print('Call Worked');
return jsonData;
} else {
print(response.statusCode);
print(response.body);
}
} catch (e) {
print(e);
}
throw Exception(' There is something wrong');
}
These are the sample instructions
Foe anyone using the Viatour api unless you are a merchant don't use the sandbox version.
var url = Uri.parse(
'https://api.sandbox.viator.com/partner/products/5010SYDNEY');
to
var url = Uri.parse(
'https://api.viator.com/partner/products/5010SYDNEY');

POST call works on Postman but not on Flutter

Future<String> loginUser(User user) async {
var body = jsonEncode({
'strlogin': user.email,
});
Response response = await post(SeguriSignAPIURL.loginUser,
headers: headers,
body: body);
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
return decode['token'];
} else {
print(response.reasonPhrase);
return '';
}
Hey! When I make this Post call on Postman I get a result, however when I run this code on flutter I get a 400 error. My headers:
final headers = {
'Content-Type': 'application/json; charset=UTF-8',
"Accept": "application/json",
};
Postman:
In Postman you do the request using form-data, but in your Flutter code, you pass json-encoded body.
You either need to use form-data in Flutter or update your server code to accept json content type.

Receiving Invalid request error from stripe while creating payment intent using Flutter

I am integrating Stripe in my flutter app, want to create payment intent using http POST request having mention here. But I am constantly receiving this error. Tried many thing!
{
"error": {
"code": "parameter_unknown",
"doc_url": "https://stripe.com/docs/error-codes/parameter-unknown",
"message": "Received unknown parameter: {\"amount\":2,\"currency\":\"usd\"}",
"param": "{\"amount\":2,\"currency\":\"usd\"}",
"type": "invalid_request_error"
}
}
My api function is this:
Future<Map<String, dynamic>> createPaymentIntent(int amount) async {
try {
var url = "https://api.stripe.com/v1/payment_intents";
var body = json.encode({
"amount": amount,
"currency": 'usd'
});
var headers = {
'Content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'authorization': 'Bearer '+stripeSecret
};
await http.post(url, body: json.encode(body), headers: headers, encoding: Encoding.getByName("utf-8")).then((response) {
if(response.statusCode == 200){
print(response.body);
return json.decode(response.body);
}
else{
return response.reasonPhrase;
}
});
} catch (e) {
return e.message;
}
}
Note: 'Content-type': 'application/x-www-form-urlencoded' is necessary for this.
You are sending a JSON encoded body to the Stripe API, but the Stripe API expects a form-encoded request body:
Our API has predictable resource-oriented URLs, accepts form-encoded request bodies, returns JSON-encoded responses, and uses standard HTTP response codes, authentication, and verbs.

Flutter http Package POST API call return 302 instead of 200, post is success in DB

Hi when I make an API post request via Postman getting the correct status code as 200 but make the same api call with flutter/http package (v0.12.0+4) or DIO (v3.0.9) package I'm getting status code as 302, but the post was successful and the data was saved on the DB. how can I get the status 200 for this or is there a better way to handle redirect in post
Found these git hub issues, but no answer on how to fix this
https://github.com/dart-lang/http/issues/157
https://github.com/dart-lang/sdk/issues/38413
Code making API post
...........
final encoding = Encoding.getByName('utf-8');
final headers = {
HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8',
HttpHeaders.acceptHeader: 'application/json',
};
//String jsonBody = jsonEncode(feedRequest.toJsonData());
String jsonBody = feedRequest.toJsonData();
print('response.SubmitFeedApiRequest>:' + feedRequest.toJsonData());
print('jsonBody:>' + jsonBody);
String url ='https://myapp';
final response = await http.post(url,
headers: headers, body: jsonBody, encoding: encoding);
print('response.statusCode:' + response.statusCode.toString());
if (response.statusCode == 200) {
print('response.data:' + response.body);
} else {
print('send failed');
}
...............
Postman Screenshot
===UPDATED WORKING CODE AS PER #midhun-mp comment
final response = await http.post(url,
headers: headers, body: jsonBody, encoding: encoding);
print('response.statusCode:' + response.statusCode.toString());
if (response.statusCode == 302) {
//print('response.headers:' + response.headers.toString());
if (response.headers.containsKey("location")) {
final getResponse = await http.get(response.headers["location"]);
print('getResponse.statusCode:' + getResponse.statusCode.toString());
return SubmitFeedApiResponse(success: getResponse.statusCode == 200);
}
} else {
if (response.statusCode == 200) {
// print('response.data:' + response.body);
return SubmitFeedApiResponse.fromJson(json.decode(response.body));
}
return SubmitFeedApiResponse(success: false);
}
}
Just add additional header,
header : "Accept" : "application/json"
The 302 is not an error, it's a redirection status code. The http package won't support redirection for POST request.
So you have to manually handle the redirection. In your code you have to add a condition for status code 302 as well. When the status code is 302, look for the redirection url in the response header and do a http GET on that url.