how save data from API - flutter - api

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);

Related

Google apps script: UrlFetchApp does not support body inside a request

trying to make a small script that would update stock in my store. This code should be working with yandex market api. They do not accept payload parameter and waiting for 'body' in the request. But at the same time look like URLFetchApp (google apps script) only can send payload and body isn't supported. Is there any way to resolve this?
function api_request(){
const url = 'https://api.partner.market.yandex.ru/v2/campaigns/2252398/offers/stocks.json'
var body = {"skus": [{"sku": "1", "warehouseId": 355055, "items": [{"type": "FIT", "count": 15, "updatedAt": get_utc_date()}]}]}
var body = JSON.stringify(body)
const params = {
method: 'Put',
'Content-Type': 'application/json',
muteHttpExceptions: true,
//'payload': body,
'body': body,
headers: {
'Authorization': 'OAuth oauth_token="abcd", oauth_client_id="abc"'
}
};
console.log(params)
var r = UrlFetchApp.fetch(url, params);
r = JSON.parse(r);
console.log(r)
}
Sending this as request:
{ method: 'Put',
'Content-Type': 'application/json',
muteHttpExceptions: true,
body: '{"skus":[{"sku":"1","warehouseId":355055,"items":[{"type":"FIT","count":15,"updatedAt":"2022-12-27T20:28:10+03:00"}]}]}',
headers: { Authorization: 'OAuth oauth_token="abcd", oauth_client_id="abc"' } }
And getting this response:
{ error: { code: 400, message: 'Required request body is missing' },
errors:
[ { code: 'BAD_REQUEST',
message: 'Required request body is missing' } ],
status: 'ERROR' }
When payload used - getting the same response.
Any ideas please? :)
I've tried to use body / payload, getting the same response

Post method via Airtable API using a Google Script

I have the following code in a Google Script:
var data = {
"records": [
{
"fields": {
"Contract Address": "test",
"0x8df3aad3a84da6b69a4da8aec3ea40d9091b2ac4": "1234"
}
}
]
};
var options = {
"method" : "post",
'Content-Type': 'application/json',
'muteHttpExceptions' : true,
// "payload" : data,
"payload" : JSON.stringify(data)
};
function tryAPost(){
var url = "https://api.airtable.com/v0/xxxxxxxxxxxxx/Balance%20Tracking?api_key=keyxxxxxxxxxx";
var response = UrlFetchApp.fetch(url, options);
//console.log(response.getContentText());
console.log(response.getResponseCode());
};
I get the following response:
422
And the data does not end up in Airtable.
The payload works in the body of a post request in Postman.
What am I doing wrong?
EDIT Per Comment:
here's the exmaple code from airtable:
var Airtable = require('airtable');
var base = new Airtable({apiKey: 'YOUR_API_KEY'}).base('xxxxxxxxxxxx');
base('Balance Tracking').create([
{
"fields": {
"Contract Address": "Thu, 03 Feb 2022 15:12:37 GMT",
"0xfecf784f48125ccb7d8855cdda7c5ed6b5024cb3": 12055358359168
Adding postman screenshot per comment:
I asked in the Airtable Forum and someone came up with a solution that worked.
Here's the link.
Here's the answer:
//
// post to Airtable (universal)
//
function atPostTable_(baseKey, tableName, payload)
{
var options =
{
method: 'POST',
headers: {
'Authorization' : 'Bearer ' + cMyAirtableAPIKey,
'Content-Type' : 'application/json'
},
payload : JSON.stringify(payload),
muteHttpExceptions : true,
followRedirects: true
};
var response = UrlFetchApp.fetch(cAirtableAPIEndpoint + baseKey + "/" + encodeURIComponent(tableName), options).getContentText();
return(response);
}

How to add header in new Onesignal React-native

Error: {"errors": ["Please include a case-sensitive header of Authorization: Basic <YOUR-REST-API-KEY-HERE> with a valid REST API key."], "reference": ["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]}
I tried as below but error as given above
sendNotification = async (data) => {
const { userId } = await OneSignal.getDeviceState();
const notificationObj = {
contents: { en: "Message Body" },
include_player_ids: [userId],
Authorization: "Basic APIKEY",
headings: { en: 'You have new notification' },
android_channel_id: 'id',
template_id: 'id',
buttons: [{ "id": "open_flat", "text": "OPEN HOSTING", "icon": "ic_menu_share" }],
include_external_user_ids: ["13245-123455"],
};
const jsonString = JSON.stringify(notificationObj);
OneSignal.postNotification(jsonString, (success) => {
console.log("Success:", success);
}, (error) => {
console.log("Error:", error);
});
};
//Sending demo
useEffect(() => {
sendNotification()
})
I am getting the error :
Error: {"errors": ["Please include a case-sensitive header of Authorization: Basic with a valid REST API key."], "reference": ["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]}
Few months i tried to send notification with fetch with contenttype and Auth header
You need to replace APIKEY with your actual API key, e.g. your API key is "MY_API_KEY123456", then the header should be Authorization: "Basic MY_API_KEY123456"
FOR ANY ONE HAS THIS ERROR
let headers = {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Basic '<API-KEY-HERE>'`,
};
let endpoint = 'https://onesignal.com/api/v1/notifications';
let params = {
method: 'POST',
headers: headers,
body: JSON.stringify({
app_id: 'App Id',
include_external_user_ids: [{'userid'},{'userid2'}], --> Optional
headings: { en: 'DATA'},
contents: { en: 'DATA'},
buttons: [{ "id": 'id', "text": 'OPEN', "icon": "ic_baseline_open_in_new_24" }], --> OPTIONAL
data: 'Extra data as json'
}),
};
fetch(endpoint, params).then(res => { console.log('sucess NotiButton') }).catch(error => console.log('error' + error));

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

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);
}

React-admin: Missing headers object in data provider

I am trying to create a custom data provider for my API. I am able to login and GET_LIST but unable to process the received data. I have adapted the required output format for the API responses and also included the Content-Range header.
With Postman all headers are returned but they seems to be missing in the "response" I am receiving in the convertHTTPResponse method.
Since headers are emtpy, the list won't appear and showing the error:
Warning: Missing translation for key: "Cannot read property 'hasOwnProperty' of undefined"
Certainly something obvious for experimented devs, please help!
Edit: Fixed it by saving the headers before converting the res.json()
myDataProvider.js
export default (apiUrl, httpClient = fetchUtils.fetchJson) => {
let url = '';
const token = localStorage.getItem('token');
const options = {
headers: new Headers({
Accept: 'application/json',
Authorization: 'Bearer ' + token
}),
};
switch (type) {
case GET_LIST:
{
const {
page,
perPage
} = params.pagination;
const {
field,
order
} = params.sort;
const query = {
sort: JSON.stringify([field, order]),
range: JSON.stringify([
(page - 1) * perPage,
page * perPage - 1,
]),
filter: JSON.stringify(params.filter),
};
url = `${apiUrl}/${resource}?${stringify(query)}`;
break;
}
default:
throw new Error(`Unsupported Data Provider request type ${type}`);
}
let headers;
return fetch(url, options)
.then(res => {
headers = res.headers;
return res.json();
})
.then(response => {
//console.log(headers);
switch (type) {
case GET_LIST:
return {
data: response.data.map(resource => ({ ...resource, id: resource.uuid })),
total: parseInt(headers.get('content-range').split('/').pop(), 10)
};
default:
return {
data: response
};
}
});
};
API call URL:
http://localhost:9000/users?filter={}&range=[0,9]&sort=['uuid','DESC']
Result with Postman:
{
"data": [
{
"uuid": "ff1xxa-ddsa-4232-b453-ed44e4dfc11d",
"email": "fr2r32442231y#domain.net",
"created_at": "2019-03-27T23:11:48.000Z",
"updated_at": "2019-03-27T23:11:48.000Z",
}
"total": 74,
"limit": 9,
"offset": 0,
"order": "DESC",
"sort": "uuid",
"success": true
}
Request Headers with Postman:
Authorization:"Bearer token123"
cache-control:"no-cache"
Postman-Token:"5e0442c7-698d-46e2-8656-50f4b10de970"
User-Agent:"PostmanRuntime/7.6.1"
Accept:"*/*"
Host:"localhost:9000"
cookie:"connect.sid=s%3AmfwRL0cVcIcBhqqGy1w6epkxjEh0nRzr.cP03XewB3Na%2B6esVOvN%2FBE5gL8gQvO%2BbWCIkC5Vbq44"
accept-encoding:"gzip, deflate"
Response Headers with Postman:
Access-Control-Allow-Origin:"*"
Access-Control-Expose-Headers:"Content-Range,X-Content-Range"
X-DNS-Prefetch-Control:"off"
X-Frame-Options:"SAMEORIGIN"
Strict-Transport-Security:"max-age=15552000; includeSubDomains"
X-Download-Options:"noopen"
X-Content-Type-Options:"nosniff"
X-XSS-Protection:"1; mode=block"
Content-Range:"users 0-9/74"
Content-Type:"application/json; charset=utf-8"
Content-Length:"13063"
ETag:"W/"3307-8yJ9evfC/wq64GCJcSnFIwWEGC8""
Date:"Thu, 11 Apr 2019 14:03:13 GMT"
Connection:"keep-alive"