I am currently trying to learn rest APIs. I want to program a food app and I'm using the Edamam food database.
https://developer.edamam.com/food-database-api-docs
If I do a request on the browser with a sample link:
https://api.edamam.com/api/food-database/v2/parser?app_id="myOwnAppId"&app_key="myOwnAppKey"&ingr=apple&nutrition-type=cooking.
Then I also get a response and all the data in JSON format.
But in Flutter I only get an error and no data output.
The code:
getFoods(String query) async {
String url = "api.edamam.com";
var response = await http.get(Uri.https("api.edamam.com",
"/api/food-database/v2/parser?app_id=$appID&app_key=$appKey&ingr=$query&nutrition-type=cooking"));
print(response.body); //Output{"status" : "error", "message" : null }
}
What am I doing wrong?
I think the problem is the second parameter in Uri.https()? i don't know what should go in there
Related
I would like to be able to read the content of a .bin file stored at a url of the form https://something/file.bin.
I tried with the http package, but the http.get doesn't work, the exception "XMLHttpRequest error." is thrown :
try {
String url = '${constants.backPrefix}${file.gpxFilePath}';
final response = await http.get(Uri.parse(url));
if(response.statusCode == 200) {
debugPrint(response.body);
} else {
debugPrint("Incorrect statusCode : ${response.statusCode}");
}
} catch (e) {
debugPrint("Exception : $e");
}
When I run this code I have :
Exception : XMLHttpRequest error.
I have no problem to access the rest of the back end (images and JSONs). I'm sure it's the correct url because when I write the url in my browser I can access to the file. The person who develops the back end told me that it could be a CORS problem.
I'm new to flutter and mobile/web development in general so maybe there's something I'm misunderstanding.
Thank you !
ok here is my json format
{
"success":true,
"user":{
"name":"example"
"email:"example#email.com"
}
}
ok by using Chopper Flutter it was easy just to get the user object by calling
response.body["user"]
however the current Chopper version ie the null safety is not stable...so how do you call this method in HTTP? to get the user object only...
Response response = await http.get(Uri.parse('enterYourUrlHere');
Map<String, dynamic> body = jsonDecode(response.body);
var user = body['user'];
print(user['email']); // prints out example#email.com"
while http request details can easily be inspected in browser dev tools(for web app), I tried to explore, where I can find the same for requests sent in flutter App, but couldn't locate it.
like for example - I can see the actual response from api by print(response), but I am talking about complete request response including headers.
I am using VScode IDE for Flutter.
update:
I want to view the headers sent like response.header. reason for the same is like I am using flutter cahe manager and the issue I am facing is like I have set the -cache control max-age=1.
so the flutter should try to fetch the same every time I access the page, which it is doing, but it is serving the page from the cache and then fetching the request. so if there is any change is on server side, it doesn't reflect when first open the page, but shows the change on every second visit.
so what I want is like if the flutter gets 304 response from server, it will serve from the cache else it should serve from the fetched data. but it is not happening.
also the response.header is not showing response code like it is 200 or 304, so that flutter can fetch or serve from cache.
Actual code being used is like this:
Future<MyUserProfile> fetchMyUserProfile() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final userid = prefs.getString('user_id');
var userProfile = await DefaultCacheManager().getSingleFile("url");
final response = await userProfile.readAsString();
if (response != '') {
print(userProfile);
// If the server did return a 200 OK response,
// then parse the JSON.
return MyUserProfile.fromJson(json.decode(response));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Profile');
}
}
Don't wanna be rude, but the information you are looking for is quite easy to find... That is if you look in the right place, like official documentation.
https://api.flutter.dev/flutter/dart-io/HttpResponse-class.html
HttpResponse class ... headers → HttpHeaders Returns the response
headers. [...] read-only
http.Response response = await http.get(url...
print(response.headers);
EDIT: Answering the sub-question that was added to the original question.
To check what the status code is you simply access it via response.statusCode
Example:
http.Response response = await http.get(url...
if (response.statusCode == 200) {
// do something
} else if (response.statusCode == 304) {
// do something else
} else {
// handle this
}
I'm testing a request to get data from an URL using dio in my Dart code.
import 'package:dio/dio.dart';
class Api {
Dio dio = Dio();
var path = 'https://jsonplaceholder.typicode.com/users';
void getHttp() async {
try {
Response response = await dio.get(path);
print(response.data);
} catch (e) {
print(e);
}
}
}
In this case it brings the result correctly.
But, I actually need get data from this URL:
http://loterias.caixa.gov.br/wps/portal/loterias/landing/megasena/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbwMPI0sDBxNXAOMwrzCjA0sjIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wNnUwNHfxcnSwBgIDUyhCvA5EawAjxsKckMjDDI9FQE-F4ca/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0KO6H80AU71KG7J0072/res/id=buscaResultado/c=cacheLevelPage/=/?timestampAjax=1588600763910
Using Postman I can access the data:
So, the problem is that, if I try to get data from that URL in my code, I get the following exception error:
I/flutter (23393): DioError [DioErrorType.DEFAULT]: RedirectException: Redirect loop detected
If this URL is redirecting, why is it working when using Postman? Anyway, how could I handle this redirected request in order to access data?
After a while, I noticed that the response to this request is coming as HTML and not as Json. So I needed to create a way to get DOM coming from the request, removing HTML tags and encoding string to Json.
I'm making a get request with the Dio library (https://pub.dev/packages/dio), but apparently it is not getting all the data in the coming json.
Here's the request:
This is the json that comes from it:
But this is the Response object I get from this request:
:
Note how the "headers" field in the json has substantially more values than my headers field in response.data.
Am I doing something wrong here?
You are returning response without extract it's content. That's OK, but you need to extract the body from response where you are calling this method:
http.Response response = await _yourApi.getData();
if (response.statusCode == 200) {
//Do what you want with body
final body = response.body;
}