I am trying to wire up my app to an external api. The external api's documentation says to make the call using curl:
curl "https://wordsapiv1.p.mashape.com/words/soliloquy"
-H "X-Mashape-Key: <required>"
My app is built with JS/React - I am unfamiliar with the above syntax. I am trying to figure out how to write this using superagent (or, if necessary, fetch).
This is what I have so far from following some other SO answers but I have no idea how to incorporate: -H "X-Mashape-Key: <required>"
My api key is stored in a .env file.
require('dotenv').config
console.log(process.env)
const request = require('superagent')
const url = 'https://wordsapiv1.p.mashape.com/words/'
//dictionary
export function getDictionaryDefinition(word) {
return request.get(`${url}/dog`).then((response) => {
console.log(response)
})
}
I highly recommend getting familiar with the basics of curl. It's worth knowing and it's everywhere. you can find nice cheat sheets here and here.
-H in curl represent a header, so in your case you'll need to add that to your request, e.g.
request.get(`${url}/dog`)
.set('X-Mashape-Key', API_KEY)
.then((response) => {...
or in fetch:
fetch("https://wordsapiv1.p.mashape.com/words/soliloquy", {
headers: {
"X-Mashape-Key": API_KEY
}
})
as a bonus, I found a nice project that "translates" curl to fetch: https://kigiri.github.io/fetch/
Related
What else should I try?
I'm currently sending a request to the DeepL API in axios, but I'm getting a 403 response due to a CORS issue.
And tried to set the option using querystring as shown here, but it didn't work. https://github.com/funkyremi/deepl/blob/master/index.ts
Also, using the library at the URL above returns 403.
Furthermore, there is no origin setting in the account settings of DeepL.
I tried using 'Content-Type': 'application/x-www-form-urlencoded' for axios headers: {}, and I also tried setting options for params: { } and not using querystring, but they didn't work.
import axios from 'axios'
import querystring from 'querystring';
export const translateDeepL = async() => {
const options = {
"auth_key": process.env.DEEPL_AUTH_KEY,
"text": 'everyday is birthday.',
"target_lang": 'JA',
};
const url = "https://api-free.deepl.com/v2/translate";
const data = await axios.post(url, querystring.stringify(options)).then(r => r);
console.log(data);
}
VM3451:1 POST https://api-free.deepl.com/v2/translate 403
the request use https with ngrok did't work also.
I also tried the GET method for "https://api-free.deepl.com/v2/usage" but got the same result.
It is definitely api-free.deepl.com since I am using the free plan.
By the way, the above code is executed as a component in React.
the DeepL API does not support being used directly from within browser-based apps. The API Key is not supposed to be shared publicly as well and should always be kept secret.
The best approach is to use a backend proxy for the API Calls.
I was encountering this same issue and couldn't find an answer. This API just didn't seem to want to talk to me via a browser.
My 'solution' was to set up an API proxy in node.
It works fine fetching from a back-end + now I can add some rate limiting etc
C.J on coding garden can explain this way better than I ever can.
You might be being blocked because of sending a request from http (your localhost) to https, try using the proxy axios config, like
const response = await axios
.get("https://api-free.deepl.com/v2/translate", {
params: {
auth_key: x,
text: y,
target_lang: z
},
proxy: {
host: "localhost",
port: 8080
}
});
return response;
};
Good Evening,
I have a function that contains a route that is a call to the Auth0 API and contains the updated data that was sent from the client. The function runs, but the app.patch() does not seem to run and I am not sure what I am missing.
function updateUser(val) {
app.patch(`https://${process.env.AUTH0_BASE_URL}/api/v2/users/${val.id}`,(res) => {
console.log(val);
res.header('Authorization: Bearer <insert token>)
res.json(val);
})
app.post('/updateuser', (req, ) => {
const val = req.body;
updateUser(val);
})
app.patch() does NOT send an outgoing request to another server. Instead, it registers a listener for incoming PATCH requests. It does not appear from your comments that that is what you want to do.
To send a PATCH request to another server, you need to use a library that is designed for sending http requests. There's a low level library built into the nodejs http module which you could use an http.request() to construct a PATCH request with, but it's generally a lot easier to use a higher level library such as any of them listed here.
My favorite in that list is the got() library, but many in that list are popular and used widely.
Using the got() library, you would send a PATCH request like this:
const got = require('got');
const options = {
headers: {Authorization: `Bearer ${someToken}`},
body: someData
};
const url = `https://${process.env.AUTH0_BASE_URL}/api/v2/users/${val.id}`;
got.patch(url, options).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
Note: The PATCH request needs body data (the same that a POST needs body data)
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
})
}
)
});
Hi I'm Learning API and I want to do a project with the the API of Udemy. Reading the documentation I see these example
curl --user {YOUR_CLIENT_ID}:{YOUR_CLIENT_SECRET} https://www.udemy.com/api-2.0/courses
curl -H "Authorization: Basic {BASE64_ENCODED(CLIENT_ID:CLIENT_SECRET)}" https://www.udemy.com/api-2.0/courses
But I don't know how to translate that into my code using superagent , right know I have this
const request = superagent
request.get("https://www.udemy.com/api-2.0/courses")
.set({myClientId}, {myClient_Secret})
.then(function(serverResult){
console.log(serverResult)})
But still appear in console
GET https://www.udemy.com/api-2.0/courses 403 (Forbidden)
In case this is helpful, this is a basic function that calls the Udemy Instructor API from Google Apps Script (GAS). GAS provides the UrlFetchApp().fetch() method. This is proprietary to Apps Script, but you still may find the structure of the header helpful.
function callUdemyInstructorAPI () {
var baseUrl = 'https://www.udemy.com/instructor-api/v1/';
var url = baseUrl + 'taught-courses/courses/?apiOptionsHere';
var params = {
"method" : "GET",
"headers" : {
'Authorization' : 'bearer mySecretUdemyAPIToken',
}
};
var response = UrlFetchApp.fetch(url, params);
}
I have a node.js express app using the Parse Javascript SDK and Parse-Server.
I've set everything up according to the guide but the JS SDK is not working.
I'm getting {error:unauthorized}. I can access my server with REST API just fine but not from within the app using the JS SDK.
I read that you have to specify useMasterKey = true for all operations with Parse-Server so:
var User = Parse.Object.extend('_User');
var query = new Parse.Query(User);
query.useMasterKey = true;
query.find().then( function(results) {
console.log(results);
},
function(error) {
console.log(JSON.stringify(error));
});
Should return the same data that this curl does (right?):
curl -X GET \
-H "X-Parse-Application-Id: myAppId" \
-H "X-Parse-Master-Key: myMasterKey" \
http://localhost:1337/parse/classes/_User
Alas, this is not the case.
Same error message when I try to run the default cloud code function:
Parse.Cloud.run('hello').then( function(response) {
console.log(response);
},
function(error) {
console.log(JSON.stringify(error));
});
Any ideas that might help? Thanks.
Got it!
What did it for me were these lines in my Express app
var Parse = require('parse/node').Parse;
Parse.initialize('app_id', 'js_key','master_key');
Parse.serverURL = 'serverURL';
Parse.Cloud.useMasterKey();
After these lines, any kind of call that requires Cloud Code usage or Parse usage were authorized
My problem was inexperience:
I am using body-parser and had the app set up to use that module's raw, json, text, and urlencoded middleware functions.
I only needed the urlencoded option. I removed the others and the JS SDK started working fine. Somehow, the other functions were interfering with the SDK.