Making a POST request to an API in JavaScript/jQuery - javascript

I've been trying to get a POST request from an API, and I'm not having that much luck in pushing it through. I'm wondering if it's because one of the parameters I'm passing is an array of objects. Been trying to get this to work for a few hours with no luck.
This post function requires two parameters, userId and classId.
//here's the api I'm calling, obviously not the actual URL
let apisource = www.exampleapi.com
//this is the class
let classId = 12345;
//these are students in the class
let userArray = [{
"name": "user1",
"userId": 101
}, {
"name": "user2",
"userId": 102
}]
I'm writing a function that takes this userArray and matches it up to a class that contains the userIds.
Here's my API call so far:
function getStudents(classId, userArray) {
$.post(apisource) + "classes"), {
userId: userArray.userId,
classId: classId
}, function(data, status) {
console.log("students in class loaded)
}
}
Nothing ever loads. Anyone have any suggestions or pointers for something I might be doing wrong?

There are a few issues here.
For example:
userArray.userId
This part of the code is definitively invalid. Arrays have indexes, not keys like objects, for example. This means you cannot access the userId param, as you haven't defined in which index it is.
Considering your array has two items:
let userArray = [
{ name: 'user1', userId: 101 }, // index 0
{ name: 'user2', userId: 102 } // index 1
];
You would need to access the user id in the following fashion:
userArray[0].userId // Returns 101
userArray[1].userId // Returns 102
As for the request itself, it could look like something like this:
let apisource = www.exampleapi.com;
let classId = 12345;
$.ajax({
type: 'POST',
url: apisource,
data: JSON.stringify({ userId: userArray[0].userId, classId: classId }),
contentType: "application/json"
});

Fist of all, you cant access to userId property of the userArray, you need to pick the object first like "userArray[0].userId" or any logic to get one element.
In other hand, i recommed you to use the fetch function, is easier to use and the code look more clean with promise.
var apisource = 'https://example.com/';
var data = {}; // the user picked
fetch(apisource , {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
source: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

It looks like you need to refactor your post implementation this way to avoid some syntax errors.
function getStudents(classId, userArray) {
$.post( apisource + "classes", {
userId: userArray.userId,
classId: classId
})
.done(function( data, status ) {
console.log("students in class loaded")
});
}

Related

Accessing an item from a web API is returning undefined

I am trying to learn how to use web APIs and am trying a little exercise where i use axios to access an api that returns quotes from famous people (bit arbitrary but its just for learning sake).
I have connected to the API fine and I can get an object back that has the quote data in it as below:
const axios = require("axios");
const options = {
method: 'GET',
url: 'https://famous-quotes4.p.rapidapi.com/random',
params: {category: 'technology', count: '1'},
headers: {
'X-RapidAPI-Key': 'secret key',
'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com'
}
};
axios.request(options).then(function (response) {
let quote = response.data;
console.log(quote);
}).catch(function (error) {
console.error(error);
});
It returns to the console as below:
{
id: 67538,
author: 'Stewart Brand',
text: "Once a new technology rolls over you, if you're not part of the steamroller, you're part of the road.",
category: 'technology'
}
However the problem comes where i want to refine it further and just console log the quote rather than the whole object.
I tried the below:
axios.request(options).then(function (response) {
let quote = response.data;
console.log(quote.text);
}).catch(function (error) {
console.error(error);
});
But that gives me an "undefined" result.
Can anyone advise me on the best way to extract just that one item from the object?
OK it turns out Amit Kumar is correct - I changed the code to console.log(quote[0].text); and it worked just fine.
the console.log(typeof quote) returning an object must be a red herring
Thanks for the help!

how to convert an array to a array of objects with additional information in react using map when doing a POST api request

I'm new with react and I'm stuck at a problem, kindly help me.
array looks like this:
surveyors=[jj,kk]
The length of array can be variable i.e.there can be more values.
what i want to send in post api is:
data:[
{
name:"kk",
is_active:True,
company:26
},
{
name: "jj",
is_active:True,
company:26
}
]
I'm using postapi like this:
const postURL = moduleURL("url");
requests({
method: "post",
url: postURL,
data: [
{
name:"kk",
is_active:True,
company:26
},
{
name: "jj",
is_active:True,
company:26
}
],
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}
if there was a fixed data i could do it but since the data in array surveyor is variable i cannot fix it.
note- company here is the company id that i have stored in a variable and it will be same for every object in array and is_active will always be true.
var supervisor=["jj","kk"];
var result = supervisor.map(s => {return {name: s, is_active:true, company:26} });
console.log(result)
use map to create a new array of objects with extra attributes;
const supervisors = ["jj", "kk"];
const modifiedSupervisors = supervisors.map(item => ({name: item, is_active:true, company:26}));
now you can use this data in api call data: modifiedSupervisors,

Response.data how to get a single data value

Here is the code that im using to try get a single element out of the data.response of an api:
client.on("message", msg => {
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://dad-jokes.p.rapidapi.com/random/joke',
headers: {
'X-RapidAPI-Host': 'dad-jokes.p.rapidapi.com',
'X-RapidAPI-Key': '0f787e5af5msh468814e0b585173p1cacafjsn7d774dfb44ff'
}
};
if(msg.content === "daddy"){
axios.request(options).then(function (response) {
console.log(response.data);
let dataDad = response.body
msg.channel.send(`${dataDad}`)
})`
and here is the response that i get from the api:
{
success: true,
body: [
{
_id: '60dd3729df8a37528bc79b03',
setup: 'How often do scientists check the table of elements?',
punchline: 'Periodically',
type: 'periodical',
likes: [],
author: [Object],
approved: true,
date: 1618108661,
NSFW: false
}
]
}
How do I use the "setup" from the response data in my code at msg.channel.send( "the "setup" ) ?
I believe, You need to do response.data.body[0].setup in order to get the first objects setup property
msg.channel.send(response.data.body[0].setup);
response.data.body is an array of objects. So, if you want to access the first object in that array, you would use response.data.body[0] So, to get the .setup property from that object, you would use this:
msg.channel.send(response.data.body[0].setup);
That will get you the setup property from the first object in the response.data.body array.

passing in json variable into sendgrid's dynamic_template_data

I'm having some trouble passing into a variable that holds a json object into sendgrid's dynamic_template_data. My setup looks like this:
const send = async (address, mentions) => {
console.log('mentions json obj', mentions)
let name = "john"
try {
let config = {
headers: {
Authorization: `Bearer ${process.env.sendgridKey}`,
}
}
let data = {
personalizations: [
{
to: [
{
email: `${address}`,
},
],
dynamic_template_data: {
name: name,
allMentions: mentions
}
}
],
from: {
email: "email#email.com",
name: "Mentionscrawler Team"
},
template_id: process.env.template_id,
}
await axios.post("https://api.sendgrid.com/v3/mail/send", data, config)
} catch (error) {
console.error(error, 'failing here>>>>>>>')
}
}
when I console.log mentions, which is json, and paste the code I get from the terminal directly into the allMentions key, it works. but when I just pass in mentions itself, nothing shows up on the sent email. I've been very confused the last few hours why this is happening. Any advice appreciated.
edit: i should also note that allmentions is an object with keys that hold arrays. So I'm looking to iterate over those arrays. Again, this totally all works if I just paste in directly what mentions is, but passing in mentions is giving me an issue.
Thank you very much,
just realized what was wrong. sendgrid's template requires a json object, so I assumed that I needed to use json.stringify on my mentions obj. Turns out I didn't need to do that, as long as all values are in string format.

JavaScript/jQuery: Passing multiple parameters to a POST request in an API

I'm having a bit of trouble managing an API request for a new project. I'm trying to practice making POST requests, and I wanted to pass multiple parameters in one POST. So far, I've tried making a for loop that loops through an array to make multiple requests, but that doesn't seem to be working. I've handled simple GET requests before, but I can't seem to figure out to pass multiple parameters to a post without rewriting the whole thing.
Here's what I have so far:
let URL = "www.exampleapi.com";
Here's the array I'm working with, they are supposed to be dogs in a kennel.
let dogArray = [
{"id": 1,
"name": "Max" },
{"id": 2,
"name": "Jack"},
{"id": 3,
"name": "Bones" }
];
The kennel the dogs are in currently has an id of 777
let kennelId = 777;
The POST request for this API requires the kennelId and the dogId (dogArray.id), so I wanted to write a function that loops though the dogArray and records the individual ids.
function getDogsInKennel(kennelId, dogArray) {
for (let i = 0; i < dogArray.length; i++) {
//the API would assign a different dogId every time it looped through
dogId = dogArray[i].id;
}
fetch(URL, {
method: 'POST',
body: JSON.stringify(({ dogId: dogId, kennelId: kennelId })),
headers:{
'Content-Type': 'application/json'
}
}).then(result => result.json())
}
getDogsInKennel(kennelId, dogArray);
As you can tell, this method isn't working. Should I scrap the entire function and try something else, or is there a way this can be rewritten to make multiple POST calls using the same array?
The main issue I am seeing is that you are not placing your code to POST inside the for look, so it will only POST once, using the last dogId assigned by the for loop
Additionally, you are not doing anything with the returned data after converting the result to JSON. If you checkout the fetch documentation here you can see that you need to add another .then to handle the returned value.
So you would end up with something a bit more like this for your function:
function getDogsInKennel(kennelId, dogArray) {
for (let i = 0; i < dogArray.length; i++) {
dogId = dogArray[i].id;
fetch(URL, {
method: 'POST',
body: JSON.stringify(({ dogId: dogId, kennelId: kennelId })),
headers:{
'Content-Type': 'application/json'
}
}).then(result => result.json())
.then((data) => {
// Process the result here
})
}
The .then is only needed if you are doing something with the result, like handling a success message/status.
I'm also not sure if you are intending to use promises to do this or not, the fetch method is promise-based. Something simpler to use may be $.post available in jQuery (more about that here)
Hope this helps:
function getDogsInKennel(kennelId, dogArray) {
let dogIds = []
for (let i = 0; i < dogArray.length; i++) {
dogIds.push(dogArray[i].id);
}
fetch(URL, {
method: 'POST',
body: JSON.stringify(({ dogId: dogIds, kennelId: kennelId })),
headers:{
'Content-Type': 'application/json'
}
}).then(result => result.json()).then((data) => {
console.log(data)
})
}
getDogsInKennel(kennelId, dogArray);

Categories

Resources