Posting to a Sheetlabs API with Axios - javascript

I am working with Sheetlabs to turn a Google Sheet into a full API. I'm having trouble finding helpful information online besides the Sheetlabs documentation, because it seems like a fairly small service at this point.
I'm using axios within a custom function in Twilio to post information to our Sheetlabs API. The API requires HTTP Basic authentication.
I've tried all sorts of variations on my axios call, trying to follow the Sheetlabs SwaggerHub Documentation but I'm running out of ideas.
const url = 'https://sheetlabs.com/records/{organization}/{dbName}';
const postData = {
trackingid: `${trackingUrl}`,
phonenumber: `${userPhoneNumber}`
}
const authParams = {
username: //sheetlabs email,
password: //access token
}
// axios function
axios.post(url, postData, {auth: authParams}).then(response => {
console.log('response: ', response);
}).catch(err => {
console.log('axios sheetlabs post error catch: ', err);
});
Any help would be greatly appreciated. I'll do my best to provide you with any additional information you need.

AJAX by default sends data in the application/x-www-form-urlencoded format, but Axios sends it as JSON. I mention AJAX because in the example page they're using $.ajax to do a network request.
Axios mentions this default on their Github here and it's something I've run into on many servers who aren't sent up to receive JSON. It might be worth a shot to try doing an npm install qs and seeing if it helps you out:
const qs = require('qs');
axios.post(url, qs.stringify(postData), {auth: authParams}).then(response => {
console.log('response: ', response);
}).catch(err => {
console.log('axios sheetlabs post error catch: ', err);
});

I reached out to Sheetlabs Support and at this time they don't support adding new records to a Google Sheet via posts. Could have sworn I saw that capability in their documentation and API though. Thank you for your responses.

Related

Next Js API not posting to an external API

so i was trying to make 2 different projects first one is my ecommerce frontend made with next js and second one is ecommerce dashboard which is also made with next js.
But when i am trying to post products from my dashboard to my ecommerce frontend nothing is happening even also I am not getting any error in console that's why i am unable to understand what is the problem.
Can anyone help me in this ? The fetch code is below.
const handelSubmit = async (e) => {
e.preventDefault();
console.log("clicked");
fetch(`http://192.168.43.53:3000/api/products`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(
name,
price,
// mediaUrl,
description,
collect,
),
})
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
Nextjs apis only work with the same origin by default, see Nextjs api Caveats for more info.
If you want to make a fully public api with Nextjs, you have to add cors, see Api Middlewares. Your code will look something like:
import Cors from 'cors'
// Initializing the cors middleware
const cors = Cors({
methods: ['GET', 'HEAD'],
})
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
If your backend api isn't defined with Nextjs, please share the code of your requested api endpoint and also the technology it uses.
I think the data you are posting needs to be in JSON first.
body: JSON.stringify(
key:value,
key1:value1
)

request method showing 403 error in node js

app.post("/",function(req,res){
// console.log(req.body.crypto);
request("https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR",function(error,response,body){
console.error('error:', error);
console.log(response.statusCode);
});
From the documentation:
All requests to our API must be authenticated with your public key.
First register an account.
Then choose one of our plans from the plans page.
Finally get your public key from the main dashboard.
You're not passing any key in your request.
You are seeing that error with 403 (Forbidden) status code because the API you are trying to use requires an API key. You can see it in their API documentation.
What you should do is following the steps mentioned in API documentation and get a API key. Then you should to use this API key as x-ba-key header for your future requests like below:
I suggest you to use axious package to make your API calls since request module is deprecated and they will not support future issues and versions. Install axios package using npm install axios command and then import it to your application file. Then make a request to the endpoint with your API key like this:
const options = {
headers: { 'x-ba-key': 'yourAPIKey' }
};
axios.get('https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR', options)
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});

Is it possible to send delete/put requests to a Azure AD secured api or get jwt Token as String using aadHttpClientFactory

I have a custom Api which I secured with Azure AD like the following tutorial:
https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient
Thats working great.
now I have the following Code to make a GET request to my custom API (working):
this.context.aadHttpClientFactory
.getClient('MY_API_URL')
.then((client: AadHttpClient) => {
console.log(AadHttpClient.configurations.v1);
return client
.get(
`MY_API_URL/SOME_ROUTE`,
AadHttpClient.configurations.v1
);
})
.then(response => {
var res= response.json();
return res;
}).then( (res: any[]) => {
...
HERE I WOULD LIKE TO GET MY TOKEN
});
So this is working how I expect it to work.
But the aadHttpClientFactory only supports GET and POST requests
Now my Idea was to just make some PUT/DELETE requests with jQuery and use the Bearer token I got above (tested with postman and its working).
But then I realised, that I won't get the token that easy.
When I console.log(AadHttpClient.configurations.v1) I only get this:
Sure I could just change my API to use POST instead of PUT/DELETE but that would be pretty ugly
Does anyone has an Idea on how I could get the token as a String to do custom requests with it?
AadHttpClient supports the fetch(url, configuration, options) method, where options can include all of the request configuration options supported by the Fetch API.
So, to make a DELETE request, you would do something along the lines of:
client
.get(
`MY_API_URL/SOME_ROUTE`,
AadHttpClient.configurations.v1,
{
method: 'DELETE'
}
);
I solved it now.
Maybe my answer will help someone later.
according to philippe Signoret's answer the is the fetch() function.
I had to use it like following:
this.context.aadHttpClientFactory
.getClient(api_url)
.then((client: AadHttpClient) => {
return client
.fetch(
MY_URL,
AadHttpClient.configurations.v1,
{
method: METHOD, //put/DELETE etc.
headers: [
["Content-Type", "application/json"]
],
body: JSON.stringify({
YOUR REQUEST BODY
})
}
)
});

How to set username and password in axios get method header

I want to fetch some data from a server via axios in my react project. When i put the url on browser and hit enter browser ask me username and password and after that, i can see the json data. But i dont know how to set the password and username in axios header in a get method. I have searched it in many forums and pages,especially this link didin't help me: Sending axios get request with authorization header . So finally i tried (many things before this, but i was more confused):
componentDidMount() {
axios.get('http://my_url/api/stb', {auth: {
username: 'usrnm',
password: 'pswrd'
}})
.then(function(response) {
console.log(response.data);
console.log(response.headers['Authorization']);
}).catch(err => console.log(err));
}
And i can not get anything. I get this error in console:
Error: Network Error
Stack trace:
createError#http://localhost:3000/static/js/bundle.js:2195:15
handleError#http://localhost:3000/static/js/bundle.js:1724:14
Actually, the api documentation mentioned that with these words:
If there is no header or not correct data - server's answer will
contain HTTP status 401 Unauthorized and message:
< {"status":"ERROR","results":"","error":"401 Unauthorized request"}
For successful authentification is sufficient to add in every request
header to the API:
Authorization: Basic <base64encode("login":"password")>
The weird thing is, when i use postman, the response send me a "401 unauthorized" response below the body section. But i can not see any 401 errors in browser's console.
Ok i found the solution. As i mentioned in the comments that i wrote for my question, there was a cors problem also. And i figured out that cors problem was appearing because of that i can not authorize correctly. So cors is a nature result of my question. Whatever.. I want to share my solution and i hope it helps another people because i couldent find a clear authorization example with react and axios.
I installed base-64 library via npm and:
componentDidMount() {
const tok = 'my_username:my_password';
const hash = Base64.encode(tok);
const Basic = 'Basic ' + hash;
axios.get('http://my_url/api/stb', {headers : { 'Authorization' : Basic }})
.then(function(response) {
console.log(response.data);
console.log(response.headers['Authorization']);
}).catch(err => console.log(err));
}
And dont forget to get Authorization in single quotes and dont struggle for hours like me :)

OAuth2 request with React Native

I am using the Yelp API for my mobile application. The Yelp API requires an OAuth2 request (consumer key, secret key, token, secret token). How do I make the request with react native?
For anyone still finding themselves looking for this answer, in ios/android:
react-native-app-auth. Hopefully they'll add react native windows support at some point.
You can make network request using fetch api,
refer http://facebook.github.io/react-native/releases/0.26/docs/tutorial.html#fetching-real-data
refer https://github.com/github/fetch for documentation
fetch(apiUrl, options)
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})

Categories