I'd like to download the JSON file which can be accessed by this url https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media. Every time I call the function I get a Error: XMLHttpRequest error. After some researches I found that this error could be avoided by adding my API token in the header. Something like
headers: {
HttpHeaders.authorizationHeader: 'Basic your_api_token_here', //here i want my token
},
But I have no clue how to get my api Token. Does anybody know how to fetch this token? May this error be caused becaus I run it on chrom flutter?
import 'package:http/http.dart' as http;
[...]
[...]
void testFunction(){
var url_string = "https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media";
var result = await getJsonFromFirebaseRestAPI(url_string);
print(result);
}
Future<String> getJsonFromFirebaseRestAPI(String url) async {
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
The JSON file result should look like this:
routes: []
It's basically empty I'm just trying to implement the function.
I use http: ^0.13.5
I get the following error:
Error: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 299:10
createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 341:28
_throw
dart-sdk/lib/core/errors.dart 116:5
throwWithStackTrace
dart-sdk/lib/async/zone.dart 1378:11
callback
dart-sdk/lib/async/schedule_microtask.dart 40:11
_microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5
_startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15
<fn>
Can anybody solve my issue?
Appreciate your time :)
In my case it works perfectly. You just need to add async to testFunction(). You have no need for JWT.
Examples:
void testFunction() async{
var url_string = "https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media";
var result = await getJsonFromFirebaseRestAPI(url_string);
print(result);
}
Future<String> getJsonFromFirebaseRestAPI(String url) async {
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
or
try{
final response = await Dio().get( 'https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media',
);
print(response.data);
}catch(e){
print(e.toString());
if(e is DioError){
print(e.response!.data);
}
}
Related
I'd like to download the JSON file which can be accessed by this url https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media. Unfortunately I was not able to download this file with the http get-function. I assume that I have some problem with the parsing since if I remove "?alt=media" it works perfectly, but unfortunately I only get the meta-json file. This is the code which I use:
import 'package:http/http.dart' as http;
[...]
[...]
void testFunction(){
var url_string = "https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media";
var result = await getJsonFromFirebaseRestAPI(url_string);
print(result);
}
Future<String> getJsonFromFirebaseRestAPI(String url) async {
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
The JSON file result should look like this:
routes: []
It's basically empty I'm just trying to implement the function.
I use http: ^0.13.5
I get the following error:
Error: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 299:10
createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 341:28
_throw
dart-sdk/lib/core/errors.dart 116:5
throwWithStackTrace
dart-sdk/lib/async/zone.dart 1378:11
callback
dart-sdk/lib/async/schedule_microtask.dart 40:11
_microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5
_startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15
<fn>
Can anybody solve my issue?
Appreciate your time :)
I did few changes on your code and it is working. There was no issue with the get function. here is the updated piece
import 'package:http/http.dart' as http;
// just a normal main to test the function in terminal
void main(List<String> arguments) async {
await testFunction();
}
// changed this to future and made it async
Future<void> testFunction() async {
var url_string = "https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media";
var result = await getJsonFromFirebaseRestAPI(url_string);
print(result);
}
// no changes applied here.
Future<String> getJsonFromFirebaseRestAPI(String url) async {
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
I managed to load the data from a Json File which is local on my Flutter Project. I also was able to fetch Data from the Internet, if the API Url was like:
https://[API-Server][parameter1:xy][parameter2:abc][API-KEY:lasgoewrijeowfjsdfdfiia]
I archieved that with this code sample:
Future<String> _loadStringFixtures() async {
return await rootBundle.loadString('assets/fixtures.json');
}
Future loadFixtures() async {
String jsonString = await _loadStringFixtures();
final jsonResponse = json.decode(jsonString);
FixturesAPI value = new FixturesAPI.fromJson(jsonResponse);
return value;
}
So far so good...
But now I am facing a problem with the API Provider RapidAPI
You can find the documentation etc. here:
https://rapidapi.com/api-sports/api/api-football/endpoints
As you can see they give some code snippets to connect to their API.
There are some for C, C#, Java, Python etc. You can look into all of them with the link above.
Sadly there is no example for Flutter.
And I do not see a way to adapt these examples.
Normally you can paste your API Key directly into the URL, but this seems not possible here? Or maybe it is?
Does Flutter also have other possibilities to receive data from an API besides the one I did?
Thank you so much in advance for your help!
It's possible to with http package and very easy. You can see in this example below...
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class APIService {
// API key
static const _api_key = <YOU-API-KEY-HERE>;
// Base API url
static const String _baseUrl = "api-football-beta.p.rapidapi.com";
// Base headers for Response url
static const Map<String, String> _headers = {
"content-type": "application/json",
"x-rapidapi-host": "api-football-beta.p.rapidapi.com",
"x-rapidapi-key": _api_key,
};
// Base API request to get response
Future<dynamic> get({
#required String endpoint,
#required Map<String, String> query,
}) async {
Uri uri = Uri.https(_baseUrl, endpoint, query);
final response = await http.get(uri, headers: _headers);
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
return json.decode(response.body);
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load json data');
}
}
}
Then get you request:
//....
APIService apiService = APIService();
// You future
Future future;
//in the initState() or use it how you want...
future = apiService.get(endpoint:'/fixtures', query:{"live": "all"});
//....
Yes it possible in flutter. Use the Dio Package in flutter which is a powerful Http client. Using dio you can set interceptors to add api key to url so you don't have to append it in every request. Setting interceptors will help you.
The class Requests set up an HttpClientRequest. The method getTeamsJsonForRequest is supposed to return the JSON response. However, the variable 'return' is not being assigned properly I assum. The print 'CONTS' in the .then response successfully prints the correct response, but printing 'myres' sections says result is null. Not sure why result is not being assigned in the response.transform section.
class Requests {
static Future getTeamsJsonForRequest(String reqPath) async{
var result;
HttpClient myhttp = new HttpClient();
String path = '/api/v3' + reqPath;
myhttp.get('www.thebluealliance.com', 80, path)
.then((HttpClientRequest request) {
request.headers.set("accept", "application/json");
request.headers.set("X-TBA-Auth-Key", "XXXXX");
return request.close();
})
.then((HttpClientResponse response) {
response.transform(utf8.decoder).transform(json.decoder).listen((conts) {
print('CONTS: ' + conts.toString());
result = json.decode(conts).toString();
});
});
print('myres: ' + result.toString());
return result;
}
}
Short answer: avoid using Future.then inside an async method.
Your print is executing before the response comes back. https://www.dartlang.org/tutorials/language/futures#async-await
Without an await any work that is done asynchronously will happen after subsequent statements in this function are executed.
Here is how I'd write this:
Future<String> teamsJsonForRequest(String requestPath) async {
var client = new HttpClient();
var path = '/api/v3$requestPath';
var request = (await client.get('www.thebluealliance.com', 80, path))
..headers.set("accept", "application/json")
..headers.set("X-TBA-Auth-Key", "XXXXX");
var response = await request.close();
var result =
await response.transform(utf8.decoder).transform(json.decoder).single;
print('myres: $result');
return result;
}
I Have A Web Service And Want To Post Data By Flutter Dart json In My WebService API Link
For REST API calls I prefer to use a library named Dio. Its way too easy to make GET, POST, PUT, DELETE etc calls using Dio.
For Example
import 'package:dio/dio.dart';
//Now like this
void _makeApiCall() async {
Dio dio = new Dio();
Response apiResponse = await dio.get('${YOUR URL}?id=$id'); //Where id is just a parameter in GET api call
print(apiResponse.data.toString());
}
And If you want to make a POST call and you need to send Form data with that do like this
void _makeApiCall() async {
Dio dio = new Dio();
FormData formData = FromData.from({
name : "name",
password: "your password",
}); // where name and password are api parameters
Response apiResponse = await dio.post('${YOUR URL}', data: formData);
print(apiResponse.data.toString());
}
Also you can map the received data into so called POJOs for better handling and usage.
If you want to know how to map the data into POJO (Objects), Just let me know.
you need to be more specif about the API and what you want to send. this is a simple example from the HTTP client library
import 'package:http/http.dart' as http;
var url = "http://example.com/whatsit/create";
http.post(url, body: {"name": "doodle", "color": "blue"})
.then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
http.read("http://example.com/foobar.txt").then(print);
Could you please provide more details on the API?
Imagine your API takes data like so, http://localhost:3000
You can make the request as follows
Future<String> create(String text) async {
HttpClient client = new HttpClient();
try {
HttpClientRequest req = await client.post('localhost', 3000, '/');
req.headers.contentType = new ContentType("application", "json", charset: "utf-8");
req.write('{"key":"value"}');
HttpClientResponse res = await req.close();
if (res.statusCode == HttpStatus.CREATED) return await res.transform(UTF8.decoder).join();
else throw('Http Error: ${res.statusCode}');
} catch (exception) {
throw(exception.toString());
}
}
OR
If you would like to post a Map (created from whatever json you have), you can use the http package. https://pub.dartlang.org/packages/http
import 'package:http/http.dart' as http;
String url = "http://example.com/whatsit/create";
http.post(url, body: {"name": "doodle", "color": "blue"})
.then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
I recommend using this packages dio package
doing post will be like this :
Future<List> postDataFromURL_list(String url, Map map) async {
// TODO: implement postDataFromURL_list
Response response;
Dio dio = new Dio();
FormData formData = new FormData.from(map);
response = await dio.post(url, data: formData);
}
I'm trying to make a ReactJS app that utilizes the Spotify API, but I keep receiving this error:
const client_id = ''; //hidden
const redirect_uri = 'http://localhost:3000/'
let accessToken;
const Spotify = {
async getAccessToken(){
if (accessToken){
return accessToken;
}
try{
let response = await fetch(`https://cors-anywhere.herokuapp.com/https://accounts.spotify.com/authorize?client_id=${client_id}&response_type=token&redirect_uri=${redirect_uri}`);
if (response.ok){
let jsonResponse = await response.json();
console.log(jsonResponse);
}
}catch (e){
console.log(e);
}
}
}
export default Spotify;
I've read around and I hear this is a server-side issue? If so, is there a work-around it? By the way I am using this https://cors-anywhere.herokuapp.com/ to prevent the CORS error.
Thanks for any help. I'll keep working on it. If I find anything, I'll post up the solution right away!