How to fetch from third party API inside backend route? - javascript

Trying to fetch JSON data from third party url and bring it to my backend route. First, I am getting query string entered into my application's url and store them to variables and use it in third party url. Second and third query strings are not entering into the url although the query string from application url has been stored properly. Wondering if there is a proper way of doing such thing.
Also, when the JSON data is fetched, is there a way to make the format it cleaner, rather than single line of an object of 47 arrays that is overflowed into 4 lines?
app.get("/api/posts", (req, res) => {
const first = req.query.first;
const second = req.query.second;
const third = req.query.third;
axios.get(`url.com?first=${first}&second=${second}&third=${third}`)
.then(response=> res.json(response.data)
.catch(err => res.send(err))
})

Related

How to access data inside Json nested objects from an API

I am using cryptocomare API to get crypto coins data within a Nextjs App. What i doing is that when a user clicks on a perticular symbol, i redirect it to the coin details page where i try to extract the clicked symbol with getServerSideProps as follows and then dynamically put in the API call and send it to the API server.
`
export const getServerSideProps = async (context) => {
const res = await fetch(
`https://min-api.cryptocompare.com/data/pricemultifull?tsyms=USD&fsyms=${context.params.symbol}`
);
const icon = await res.json();
return {
props: {
icon,
},
};
};
`
This call returns a json object of nested objects and it goes to 2-3 levels deep. On Top it looks like following:
API call response
Inside my code, I want to access the data Object -> RAW -> (whatever the user clicked on). But, Since the Symbol or coin queried by the user is dynamic (means i can't predict what is clicked) I never know what to query. SO i tried this to access the data object.RAW[0]
In principal it should give me the whatever object is inside the object.RAW But it returns undefined
Can please someone guide me , how can i get the data inside object.RAW without knowing what is inside?
Thanks!
I have tried object.RAW[0] to access the data...,....
You can use Object.values(object.RAW) to get an array of the values inside RAW (assuming RAW is not undefined)
Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

Formatting a JSON Response to build a URL

I'm incredibly stuck on trying to format receive a JSON response, and format it. Order of operations:
Query a REST API endpoint (https://endpoint.com/api/v1/employee?id={username})
Receive JSON response: {"employee":{"full name":"Example Name","function":"Role","office":"Office Location",team":"Team 1|Team 2|Team 3|"}}
In my base.js file within my django app, I am hoping to extract the team strings and pass them into another URL. What way can I do this? When I $.getJSON from the endpoint I receive responseJSON, responseText, etc. but I'm unable to pull them out/use them in any way.
In order to fetch and parse json I would suggest you to use the following fetch structure:
fetch('https://endpoint.com/api/v1/employee?id=username')
.then(response => response.json())
.then(data => {
let teams = data.team.split('|');
// Do something with team names
});
Let's break down what this does per line:
First we use fetch to request data from the defined url
Then we convert the response to a json object
Finally we retrieve the string with team values using the data.teams statement, after which we immediately convert the list of team names to an array by using split and the defined delimiter |.
After this you should be able to do whatever you'd like with the team names. You could use them to make another API call as well. If you're interested, be sure to checkout the fetch documentation, as well as the split documentation if you are not yet familiar with that function.
The solution above assumes that the response will be a 200, for error handling you should check out the fetch documentation above.

Error in passing a parameter string with period to spring-boot backend

I am making an api call from my front end service to my backend service which works most of the time, however it breaks when there is a period in the form name. This is the api call my front end makes:
static GetMetaDataInfo(returnName) {
return axios.get(`${ROOT_URL}/api/v1/filing-metadata/metadata/${returnName}`, {
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.data)
.catch(error => console.log(error));
}
My back-end controller is mapped to "/api/v1/filing-metadata" and the following request goes to "/metadata/{level1}/{level2}/{form_name}"
The return name is in the form of {Country}/{State}/{FormName}. Take "US\CO\CO DR-0251" as an example (this is an example that works when I make the call).
Using "US\CO\CO DR-0251" in the backend, {level1} corresponds to US, {level2} corresponds to CO, and {form_name} corresponds to CO DR-0251. By using this entire name, I query the database for a match, and return the data associated with this form name.
My issue comes when a make the call with a form name that has a period in the name, for example: "US\NV\NV_TXR-02.01"
In this case the {form_name} when I make the request is "NV_TXR-02" instead of "NV_TXR-02.01" which fails to find a match when I query the data base. The form name is not something I can change, is there a way to keep the text that it is omitting when I make the call to my spring-boot back end?
Thank You to Steven B. for his comment, it turned out to be the solution to this question. I just needed to add a '/' character at the end of the url string. I added one at the front end code as well as the back end api and every case works now, even if they have periods.

How to get data from multiple url's in Reactjs?

I want to get json data from multiple url's and display it on frontend.
Following are the url's:
1) localhost:3000/api/getdata1
2) localhost:3000/api/getdata2
3) localhost:3000/api/getdata3
Instead of using .fetch() on each of the url's like below:
.fetch('localhost:3000/api/getdata1')
.fetch('localhost:3000/api/getdata2')
.fetch('localhost:3000/api/getdata3')
Can this be done in more efficent way in ReactJs ?
I was trying:
const dataurls = [
'localhost:3000/api/getdata1',
'localhost:3000/api/getdata2',
'localhost:3000/api/getdata3'
];
const promisedurl = dataurls.map(httpGet);
Promise.all(promisedurls)
.then(data=> {
for (const d of data) {
console.log(d);
}
})
.catch(reason => {
// Receives first rejection among the Promises
});
Please suggest which one should be used or is there any efficient way to do get data from multiple url's.
ReactJS is a View layer library. It has nothing to do with how you aquire any data from server.
Even state libraries, like Redux and Reflux do not implement any method of fetching data. In most cases you do that in your custom app code. Sometimes using extra libraries (e.g. Redux middlewares).
So, yes: your Promise.all(<several https requests here>) is the most natural way to achieve that.

How should I parse query paramters to a sql query

How should I be parsing request query parameters and translate that into a database query?
Say I have a url of /projects that can sometimes be called with query parameters such as, /projects?sort=status&part=123 or possibly /projects?priority=1&owner=baz
In my express app I have route defined as:
app.get('/projects', (req,res) => {
let query = parse_request(req.query) || default_query;
database.execute(query, result => res.send(result));
});
I will be use a custom parse_request function to return the database query I want to execute based on the query parameters or a default query if no parameters were passed.
Is this a sane approach or should I be going about this a different way? Seems like the parse_request function could be a bit involved depending on how many query string options I would like to handle.

Categories

Resources