How to get User's followers using spotify sdk in flutter? - flutter

String authToken=await getAuthenticationToken();
final response = await http.get('https://api.spotify.com/v1/me/following', headers: {
'Authorization': 'Bearer $authToken',
});
print('Token: ${authToken}');
print(response.body);
I am getting an error:
Insufficent client scope

Related

How to send raw data in flutter http

I wanted to send raw data in flutter http and the data doesn't look like JSON
Here's how I done that in Postman
and tried this in flutter using http,
Response res = await post(
Uri.parse(baseUrl + endPoint),
headers: {'Client-ID': clientId, 'Authorization': 'Bearer $accessToken'},
body: jsonEncode('fields *'),
);
and got this in console,
Error: XMLHttpRequest error.
Add it as this
var headers = {
'Accept': 'application/json',
'Content-Type': 'text/plain',
};
var request = http.Request('POST', Uri.parse('Your url'));
request.body = '''fields *''';
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
Or you can easily see it being implemented in Postman's code request to the right just select the code icon and choose http-Dart

Can't get auth token stored in flutter secure storage to headers

I am making flutter app using API and I have a problem. When I want to get auth token to make request, flutter says that "Expected a value of type 'String', but got one of type '_Future'". How can I make a request with auth token without that error?
My login function, where I write the token:
loginUser() async {
final storage = new FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/login");
await http
.post(uri,
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"username": emailController.text,
"password": passwordController.text
}))
.then((response) async {
if (response.statusCode == 200) {
var data = json.decode(response.body);
await storage.write(key: "token", value: data["token"]);
print(data["token"]);
} else {
print(json.decode(response.body));
}
});
}
My getdata function, where i use the token:
getdata() async {
final storage = FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
await http.get(uri, headers: {
"Content-Type": "application/json",
"Authorization": await storage.read(key: "token")
});
}
try this code
String token = await storage.read(key: 'token');
//make sure if there is no Bearer just token in that case just pass the token
var headers = {
'accept': 'application/json',
'Authorization': 'Bearer ${token}',
};
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
Response response = await http.get(
uri,
headers: headers
);
print (response);

When I use flutter http library with headers authorization token, its shows 500, in console. but in postman all okay

Here is my code, I also tried using retrofit but I failed and it shows 500 and "message": "Undefined index: token". but in postman, it shows 200. how can it be possible?
Also tried
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
Future getCertificateList() async {
final url = Uri.parse(
'https://portal-api.jomakhata.com/api/getCertificateList');
final response = await http.get(url,
headers: {
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI4NjE0MDcyLCJleHAiOjE2Mjg3MDA0NzIsIm5iZiI6MTYyODYxNDA3MiwianRpIjoiRnRjaGllbTFFdVlsYXZidyJ9.O24U0XGFiZdfXRGUP5xYD82-LisSbMsCtVZnuG6iTiY',
},
);
print(response.statusCode);
print(response.body);
return response.body;
}
In my console it's print 500
this is postman request image
try this code:
Future getCertificateList() async {
final uri = Uri.https('https://portal-api.jomakhata.com','/api/getCertificateList');
final response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader:
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI4NjE0MDcyLCJleHAiOjE2Mjg3MDA0NzIsIm5iZiI6MTYyODYxNDA3MiwianRpIjoiRnRjaGllbTFFdVlsYXZidyJ9.O24U0XGFiZdfXRGUP5xYD82-LisSbMsCtVZnuG6iTiYv',
HttpHeaders.contentTypeHeader: 'application/json',
});
print(response.statusCode);
print(response.body);
return response.body;
}

GET request is showing "406 - Not Acceptable" in Dart for http package Flutter

I am requesting the following Get request but getting "406 - Not Acceptable" response. Here I have attached the request code:
final Map<String, String> tokenData = {"Authorization": token};
var response = await http.get(url, headers: tokenData);
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
} else {
print('Request failed with status: ${response.statusCode}.');
print('Request failed with reason: ${response.reasonPhrase}.');
}
Change your tokenData as follow:
final Map<String, String> tokenData = {
'Authorization': token
'Content-type': 'application/json',
'Accept': 'application/json',
};
It will work if you are getting JSON as a response.

How to remove quotation and symbols while decoding from JSON value? Flutter

This is the code to get my auth token.
Future <String> getToken() async{
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('token');
}
When i print the token it gives me this json value with double quotation mark.
I/flutter (14710): "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiZDQzZjFjNWZjZDQxYjIzYzllNGU2ZWIyZjQ1M2FmZDgwOTJiNGZmNDAyYjI0OTBmM2RiYTUzMTgzYTU2ODZjNTNiNzVmMDY3ZmIzMmNjMjUiLCJpYXQiOjE1OTA0MDg2NjksIm5iZiI6MTU5MDQwODY2OSwiZXhwIjoxNjIxOTQ0NjY5LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.3YYdR8P1_XzK--VLAwT5gxmkyLZPMuvQhzQQ5OOl_nv0jriPwFY9sqHdL_wiqpAA5vtgBOnyAwZ2kSI_BgDzsKZzY2vMVa47Tyuz87uEFZ7-aHYvNY_r4T_gIkwAuLwc8qN2kuytFjEtuq-iQUiWgEzp5y2n3BDlzXZ7rZi5Xp1_y_6_ysII9RQtX37LuDFt3AIRbYLGDBAilPHi0iJB_jQqWqH8J1mUzCsArj2VuSel7kERqpwFz-SwOOS4EA7CaoOuOlleOpynBalTK9vm1vU3n81K4TAgNq-Mg9CsiFMVQULURdmku7-2gcc3VS8vBXo9OlEgzqmGjLDvIy8_-LCcwuoSVC2DL2t2PIcNUDKQsBu1GBPQ99wzHcnyEpvjVRkg7v4zQWtlIUY6PcLjNf_vnfuXuCERAwBwjS86T7n8ZscfmVVebISVvAKyDN6YhW41hnUw-AZYRLtuhbE8Z48V0tLfLw9aeVr-Qe2mlaYj0LqGYlqBLqUtRl9HSaA9USa6tQ1KQJvF5_6JPcIBJuSkEsrY9n1xhnCViAiyFVF4XWbtToULn69B2UtoXw1X8y_Wek_T7D7t0fi5KWKj8QHO6yI3ZIWViERS2K6n7mnL_3z_7CNeewVxmqMXNdeWl7yPmAMzUAv6z7pWm-R1Qpv7tNVj4-FfQAk3vOm56hE"
This is how i used the token you get the post from api but it isnt working.
Future<Model> ViewWelcomeScreen() async {
String url = '$baseurl/post/20';
ApiService().getToken().then((value){
token = value;
});
final response = await http.get(url, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
print(token);
if (response.statusCode == 200) {
var test = json.decode(response.body);
var jsonResponse = test['data'];
return Model.fromJson(jsonResponse);
} else {
throw Exception('Failed to load data');
}
}
Future<Model> ViewWelcomeScreen() async {
String url = '$baseurl/post/20';
ApiService().getToken().then((value){
token = value;
});
final response = await http.get(url, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
print(token);
if (response.statusCode == 200) {
var test = json.decode(response.body);
var jsonResponse = test['data'];
return Model.fromJson(jsonResponse);
} else {
throw Exception('Failed to load data');
}
}
code is wrong in a way, think you have async and then both on the same function, why?
ApiService().getToken().then((value){
token = value;
});
here you're saying I want token and I don't need to be awaited then you go and try to use that variable
final response = await http.get(url, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
see in flutter every async-await works like event loop in javascript
I write async
normal code
using then in 1. function
dependent code in 1. as async-await
what will be the output?
event loop will be having 1,2,3,4 as async functions
first, it will run 1 and as soon as it receives normal code it runs normally but if it receives then it will understand that this result is not important so let me do rest of the work and will come back to execute 3rd then function so it will run 4 and then 3rd function
but you want token so
ApiService().getToken().then((value){
token = value;
});
replace this to
token = await ApiService().getToken();
your service might need token and that's the reason it's not 200 status code.
If you just want to remove the "" from the string, then just use the replaceAll method
String string = '"foo"';
//Output: 'foo'
string.replaceAll('"', '');