Formatting a JSON Response to build a URL - javascript

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.

Related

How do I export an entire space in storyblok in js?

From reading up on the management API, I think I should be able to fetch data from storyblok from inside my js. The first thing I'm trying is to export my entire space so that I can have an external backup. From reading the documentation, I think the following should work, but it gives me a 401. What is the correct syntax for this?
// spaceId is discovered in Settings / Space
fetch(
`https://mapi.storyblok.com/v2/spaces/${spaceId}/export.json`,
{
headers: {
Authorization: managementToken, // this was created in My Account / Account Settings / Personal access Token
},
}
)
.then(async (res) => {
const json = await res.json()
console.log(json)
})
.catch((err) => console.log(err));
I was also looking to export a single story, which I think the correct URL should be:
`https://mapi.storyblok.com/v2/spaces/${spaceId}/stories/${storyId}/export.json`
I can't figure out how to determine the storyId, though. I tried the UID but that didn't work and the example showed an 8 digit number. Where do I find this number?
Note: I'm in the US, and for the regular fetches I had to use the domain https://api-us.storyblok.com so I tried adding -us and that didn't work.
Note: I will eventually be trying to add and modify stories in this same js file. Also, be able to "restore" the entire space if necessary. I hope the solution to the above will be applicable to all the rest of the calls I'll be attempting.
Note: The app is written in Nuxt 3 and I'm using useStoryblok() successfully to retrieve data. I could fulfill the above requirement to back up the entire space by iterating through everything there, but that seems like more work than is necessary, and it doesn't solve my problem with the other calls I need to make.
The management API is still on v1, it's only the content API that's v2:
https://www.storyblok.com/docs/api
That probably should help with your 401. I actually also assumed I had to use v2 :)
As how to get the story ID: yes, it's the simple ID, not the UUID.
You get it by listing some stories .../v2/spaces/SPACEID/stories?with_slug=abc.
Or look at the draft/published JSON in the Storyblok UI.

Call a specific array in a JSON API call

I'm trying to call the API but it doesn't return me anything.
I'm calling it like: res.on('data', d => { const RetrieveFromApi = JSON.parse(d).FLUX.quote.USD.price;.
The API is successfully called since I can see it in the API history, and data is defined as d.
Can you help me please?
from your screen provided in comment, you passed one property you don't access to it which is data
So just add property data before FLUX
JSON.parse(d).FLUX.quote.USD.price;
^data.FLUX.quote.USD.price;
From the image of the log the object seems incomplete at the end, did you try to use JSON.stringify(d) to see if there are any errors on the json object? or copy the response on https://jsonlint.com to check?
Because the error message points that the parse doesn't find a valid json object, maybe that is the whole point.
And the other tip is to try to store the value of JSON.parse in an variable before trying to access his values.

i want to retrieve location from promise aaray of open cage geocoding by passing lat and log but dont know how to retrieve the value

i want to retrieve the location from the fetched API of open cage geocoding which has the following structure
this picture contains the structure of data strogae
pls help me out
When using fetch you can usually accomplish it like this:
fetch("https://api.opencagedata.com/geocode/v1/json?q=51+16&key=YOUR_KEY")
.then( response => response.json())
.then( data => console.log(data.results))
The first line returns a response Promise. The second line contains instructions on how to parse the response body. In this case, you want to parse JSON, hence, you call res.json().
More on the latter part can be found here.

How to fetch from third party API inside backend route?

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

Dealing with data in axios response

I'm new to axios.
In the past when I've made http requests I'm used to getting back an array/array of objects and this allows me to easily format the data how I want by using functions such as map and reduce. I then would render it to the DOM.
I've noticed in the response I get back is an observer object. How would I go about making the request so it gives me back an array? What is the standard for dealing with this observer object?
getSomething (myId) {
return axios.get('/api/getSomething', {params: {'id': myId}})
.then(response => console.log(response.data))
.catch((promise) => this.handleError(promise));
}
Thanks
EDIT:
Updated code.
To clarify, when I call getSomething() response.data is an object even though I am sending it as an array on the backend. I am assuming that axios is changing this array to an object. The object has a bunch of extra properties like __ob__ and get 0
So I found the issue. If you pass through an array where the keys are not in order e.g. [1: [], 5: [], 6:[]]. Javascript will change it into a observer object which has different properties in order to maintain the keys. This issue is not related to axios.
You can do something as simple as the following to access the data:
axios.get('/some/url').then(response => {
console.log(response);
});

Categories

Resources