Post method via Airtable API using a Google Script - api

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

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

G-Sheet script to post a message on Guilded using its API

I am trying to create a script to post a text message in a chat on Guilded, but so far I get a "POST is not allowed"
Message should be "inPrivate" so a mention of the targeted member is required.
Google sheet test file
my script:
function message () {
var url = "https://www.guilded.gg/api/v1/channels/";
var channelid = "d2ba*****";
var key = "Bearer gapi_*****"; //Q-P API temp-bot
const message = {
content : "It's alive!",
embeds :[{
author:"API",
mentions:"Raven_test",
}],
isPrivate : true,
}
const params = {
method: "POST",
headers: { Authorization: key },
contentType: "application/json",
payload: JSON.stringify(message),
muteHttpExceptions: true,
};
Logger.log(JSON.stringify(params));
const response = UrlFetchApp.fetch(url + channelid + "/messages/", params);
var data = JSON.parse(response);
Logger.log(data);
}
Guilded's API
I don't understand what I'm doing wrong (but I'm a newbie, so it makes sens)
POST is still not working, with the same answer, however, if I use the PUT method, I can update a message if written by the same bot (I just need to add the messageid in the url after /messages/
function postmessage () {
var url = "https://www.guilded.gg/api/v1/channels/";
var channelid = "d2bac803-****-****-****-a609ab9c58c4";
var key = "Bearer gapi_******"; //Q-P API temp-bot
var server = "wlVKV***"
var messageid = "ae6f1693-****-****-****-c9984d4142de";
var author = "****";
const message = {
"type": "default",
"serverId":server,
"channelId":channelid,
"content" : "test #Aaron Raven ",
"mentions":{
"users" : [{"id":author}]
},
"isPrivate":false,
"isSilent":false
};
const params = {
method: "put",
headers: { Authorization: key },
contentType: "application/json",
payload: JSON.stringify(message),
muteHttpExceptions: true,
};
Logger.log(JSON.stringify(params));
// const response = UrlFetchApp.fetch(url + channelid + "/messages/" + messageid, params);
const response = UrlFetchApp.fetch(url + channelid + "/messages/" params);
var data = JSON.parse(response);
Logger.log(response);
Logger.log(data);
Logger.log(params);
}
Another issue (aside POST method) is that "mentions" doesn't work; it appears as basic text, and not as a user tag/link
Kind regards,

DialogFlow -CX with React Native

Is there any way to implement DialogFlow-cx directly with React native App as DialogFlow ES version does?
I am trying with the REST API also But not working.
I want to Call the Dialogflow CX API from my React-Native App.But I am getting 404, I have downloaded the private key as a JSON file from the service Account also.
Here is a sample code that I have tried
let data = {
"queryInput": {
"text": {
"text": "Hi!"
},
"languageCode": "en"
},
"queryParams": {
"timeZone": "Asia/Colombo"
}
}
fetch(DEFAULT_BASE_URL + this.projectId +"/locations/"+ this.location + "/agent/"+ this.agentId +"/sessions/" + this.sessionId + ":detectIntent", {
method: "POST",
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer ' + this.accessToken,
'charset': "utf-8"
},
body: JSON.stringify(data)
})
.then(function (response) {
console.log("RESPONSE=== ");
console.log(response);
// var json = response.json().then(onResult)
})
.catch(onError);
};
I changed the agent to agents in URL and it worked.
Here is a reference doc From Google https://cloud.google.com/dialogflow/cx/docs/quick/api

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

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"