authorization type bearer token on postman and request data from the API which requires a token bearer with flutter - api

im trying to request data from my API and to get the data, it requires a bearer token which can be obtain by log-in. and as a frontend I created a function to save and request from the UI to the API. I'm using flutter framework for the UI.
I've managed to create a function to store the bearer token generated at login, which keeps the user logged in. and it works by saving the bearer token in sharedpref.
login() async {
final response = await http.post(
"https://api.batulimee.com//v1_ship/login_app",
body: {"email": email, "password": password},
);
final data = jsonDecode(response.body);
String status = data['status'];
String pesan = data['message'];
String apikey = data['data']['apikey'];
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('apikey', apikey);
if (status == "success") {
Navigator.of(context).pushReplacement(PageRouteBuilder(
pageBuilder: (_, __, ___) => new bottomNavBar(),
transitionDuration: Duration(milliseconds: 600),
transitionsBuilder:
(_, Animation<double> animation, __, Widget child) {
return Opacity(
opacity: animation.value,
child: child,
);
}));
print(pesan);
print(apikey);
} else {
print(pesan);
}
}
heres the response.
{
"status": "success",
"data": {
"apikey": "UUFmb0w3WlI4Q01qOWRTamgxOFVZRjhIeWhFMkN3T205R20xZXNpYw==",
"id_user": 50,
"id_role": "8",
"name_role": "Ship Owner",
"email": "me#gmail.com",
"phone": "0210201",
"saldo": "0",
"photo": "https://cdn.batulimee.com/foto_user/avatar.png"
},
"message": "login successfully "
}
and now I want to create a function that can get user profile data, and where to get this data requires the bearer token which I got from login. I need this so that the user can edit their name, password, or other data in the user's profile and save it.
My backend has created the API get my_profile. which I explained earlier, to get this requires a token bearer that is the same as the token bearer we got earlier from login. And now it's my job to get the get my_profile data using a function in flutter.
heres the response from the API get my_profile.
{
"status": "success",
"data": {
"id_user": 49,
"id_role": "8",
"name_role": "Ship Owner",
"first_name": "a",
"last_name": "f",
"email": "afriansyahm86#gmail.com",
"phone": "082258785595",
"saldo": "0",
"company_name": "aa",
"company_address": "jl kav pgri",
"photo": "https://batulimee.com/foto_user/avatar.png"
},
"message": "get profile detail successfully "
}
How is the function to store the bearer token into Authorization so I can get my_profile data ? please help me.... :(

make an api class :
import 'package:http/io_client.dart';
class Api {
String _token;
final Client http =IOClient(HttpClient()
..badCertificateCallback = _certificateCheck
..connectionTimeout = const Duration(seconds: kConnectionTimeoutSeconds));
static bool _certificateCheck(X509Certificate cert, String host, int port) =>
host.endsWith('EXAMPLE.com'); // Enter your url for api here
String GetToken() {
return _token;
}
Future<bool> setToken(String token) async {
_token = token;
return Future.value(true);
}
Map<String, String> get headers => {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer $_token",
};
}
in your login use the setToken:
await _api.setToken(apikey);
next for your profile or any request in api class:
Future<ProfileResponse> getProfile() async {
var url = "$urlPrefix/api/v1/profile";
var response = await http.get(url, headers: headers);
if (response.statusCode != 200) {
print(
"$response");
var parsed = json.decode(response.body);
var message = parsed["message"];
if (message != null) {
throw message;
}
throw Exception(
"Request to $url failed with status ${response.statusCode}: ${response.body}");
}
// return the response you want
return json.decode(response.body);
}

Related

how save data from API - flutter

I'm workin on API request.I would like to save all data recieved from API and reuse it in second method as parametres .
API response :
{
"code": 0,
"message": " success",
"data": {
"data": [
{
"id": 14,
"boxIdentifiant": 1924589682265255,
"user_id": 53,
"boxName": "box12",
"proprietaire": 21625147147,
"adress_circulation": "Tokyo",
"gps_lat": null,
"gps_long": null,
"status": "normal"
}
]
},
"error": [],
"status": 200
}
I recieve data above by this method :
Future<UserBox> fetchBoxes() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var url = Uri.parse(ApiUtil.GET_ALL_BOXES);
var response = await http.get(url, headers: headers);
var body = jsonDecode(response.body);
var data = body['data']['data'];
List<BoxModel> boxes =
List.generate(data.length, (index) => BoxModel.fromJson(data[index]));
final userbox = UserBox()..boxes = boxes;
return userbox;
}
How i can save all data ?
UserBox data = await fetchBoxes();
secondMethod(data);

how to retrieve data form post API flutter

im beginner in flutter, i want to get data form API but the API is 'post' tipe. how to retrieve the data? please help me. thank you (:
example, i have API data "post" and the data is 'phonenumber', 'password', 'address', 'name', 'class'. how to get all of the data and show/display it all?
I have a code snippet of it which you can refer
This is about calling the POST API of the student and pass the credentials as a body.
Future<Map<String, dynamic>> loginUser(String phone, String pass) async {
http.Response response = await http.post(
EndPoint.Login,
body: jsonEncode(
{
"phonenumber": phone,
"password": pass,
},
),
headers: {"Content-Type": "application/json"},
);
var parsed = jsonDecode(response.body);
Map<String, dynamic> authfailed = {};
if (parsed['message'] == "Auth failed") {
authfailed['message'] = "Auth failed";
return authfailed;
}
// print(parsed);
return parsed;
}

Expo - React Native: How to read User data from Google Fit API

thanks in advance for any assistance that can be provided. My goal is to use OAuth2 to get users’ step data from the Google Fit API. I am able to authenticate using Expo's expo-app-auth package, and receive an accessToken, but, when I try to read from the Fit API, I get an error that the authentication credential is missing.
Relevant Code:
let config = {
issuer: 'https://accounts.google.com',
scopes: ['openid', 'profile', 'https://www.googleapis.com/auth/fitness.activity.read'],
/* This is the CLIENT_ID generated from a Firebase project */
clientId: 'xxx.apps.googleusercontent.com',
};
let authState = await AppAuth.authAsync(config); // this returns an idToken, accessToken, list of scopes configured, including the fitness.activity.read
const url = 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate';
const today = new Date().getTime();
const past = today - (5 * 24 * 60 * 60 * 100);
const body = {
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 },
"startTimeMillis": today,
"endTimeMillis": past
}
const header = {
'Content-Type': 'application/json',
'Authorization': `BEARER ${authState.accessToken}`
}
const req = await fetch(url, {
method: 'POST',
headers: header,
body: JSON.stringify(body)
});
const resp = await req.json();
/*
Object {
"error": Object {
"code": 401,
"errors": Array [
Object {
"domain": "global",
"location": "Authorization",
"locationType": "header",
"message": "Login Required.",
"reason": "required",
},
],
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED",
},
}
*/
I am able to produce this issue using a built apk on a real device. For the standalone build, I am using an OAuth2 clientId from Google Console as clientId in the config, and the Fitness API is enabled.
Does anyone know what I might be doing incorrectly?

405 error with JIRA REST API using node js

I am trying to create an automated JIRA ticket using the REST API but I keep getting a 405 error.
I am using the examples here: https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
Also, when I visit the post URL directly I do not get any errors so I doubt it is a server issue. Any ideas?
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to Jira.
var loginArgs = {
data: {
"username": "user",
"password": "pass"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("https://jira.mydomain.com/rest/auth/1/session", loginArgs, function(data, response) {
if (response.statusCode == 200) {
//console.log('succesfully logged in, session:', data.session);
var session = data.session;
// Get the session information and store it in a cookie in the header
var args = {
headers: {
// Set the cookie from the session information
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
// I copied this from the tutorial
"fields": {
"project": {
"key": "REQ"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Request"
}
}
}
};
// Make the request return the search results, passing the header information including the cookie.
client.post("https://jira.mydomain.com/rest/api/2/issue/createmeta", args, function(searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
I am expecting the Jira ticket of type REQ to be created with the details I added in the fields section.
I believe you are using the incorrect REST API; what you're currently doing is doing a POST to Get create issue meta which requires a GET method, hence, you're getting a 405. If you want to create an issue, kindly use Create issue (POST /rest/api/2/issue) instead.

Receiving a BAD REQUEST (400) response with Basecamp API 3 from a Node Express application

The same request including the access token is working with CURL and Postman.
The code from Postman (masked credentials and ids) is included.
var http = require("https");
var options = {
"method": "GET",
"hostname": [
"3",
"basecampapi",
"com"
],
"path": [
"<MASKED ACCOUNT ID>",
"my",
"profile.json"
],
"headers": {
"Authorization": "Bearer <MASKED AUTH TOKEN>",
"Cache-Control": "no-cache",
"Postman-Token": "92fc7993-57aa-47f7-aaae-44925dd37f3e"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();
Use NodeJS Request instead of NodeJS Native when creating code from a Postman request.