How can I understand the use of query parameter in REST api? - javascript

As a learner, I am trying to call the rest api. For example, you can see and copy the url from api provider as they listed on that link page.
https://docs.api.jikan.moe/#tag/top/operation/getTopAnime
function App() {
const [topAnime, SetTopAnime] = useState([]);
useEffect(() => {
fetch(`https://api.jikan.moe/v4/top/anime`)
.then((response) => response.json())
.then((data) => {
console.log(data);
SetTopAnime(data);
})
.catch((err) => {
console.log(err.message);
});
}, []);
But the question is; this does not let me to call a specific data I want to call.
To do that, I need to add some query parameters as api page written for developer.
Now, I see several examples that someone set it as follows:
const getData = () => {
axios
**.get(`${apiTop}?sfw=true&limit=20`)**
.then((res) => {
return setData(res.data.data);
})
.catch((error) => {
console.log(error);
});
};
that .get method and following code makes sense. But how that developer who coded that line knew '?sfw=true&' such thing?
If I don't understand this; what topic could be the one I should review then? I believe I understand what promises and fetch are, but not sure focusing on 'query parameter' is the right thing to solve my problem.
tl;dr
To call a specific data from getTopAnime, how should I set query parameters? (with my understanding, https://api.jikan.moe/v4/top/anime/type/movie
or
https://api.jikan.moe/v4/top/anime?=query/type/movie
is the limit to expand the thoughts.
Thanks...

From the documentation of the API -- https://docs.api.jikan.moe/

There must be API documentation where you can read about these URI structures.
Though a real REST service sends you hyperlinks with URIs or URI templates which you follow, so you need to know what type of hyperlink watch for and the service gives you the URI structure. This is called HATEOAS constraint.

Related

How to get single value from request response

I started writing a program that will automate user actions, by now it's meant to be an easier menu to make faster actions by just sending requests to the official website by clicks on my own page. (something like web-bot but not exactly).
My problem is when i send login request in response i get back user_id, server, session_id etc. And I need to save that session_id to make the other actions.
How can i save this to variable.
All in JavaScript.
I was looking in the internet since yesterday for an answer and i still can't find (or understand) how to get this
I tried
function login(){ fetch('url', { method: 'POST', headers: { //headers }, body: //my Id's }) })
//There's the problem to solve
.then(res => res.text()) .then(data => obj = data) .then(() => console.log(obj)) console.log(body.session_id);
// I even tried the substring but 1. It won't work as I want because There are sometimes //more and less letters. 2. I get and error "Cannot read properties of undefined (reading //'substr')"
`session = obj;
session_id = session.substring(291,30)
console.log(session_id)`
It looks like you're using the text() method on the Response object returned from fetch(), which will give you a string representation of the response.
You probably want to be using the json() method instead, and from that you can get your session_id.
This guide has some more useful information that may help you: https://javascript.info/fetch
Ok it works now with
`async function login(){ let session = await fetch('url', {
//code
}
let result = await session.json();
console.log(result);
session_id = result.data.user.session_id;
user_id = result.data.user.id;`

Access query parameters using axios

I am using React in the frontend and Django in the backend and I am currently doing the API integration for which I am using Axios.
So in the frontend side I am calling a URL like this
http://localhost:3000/attempt/?quiz_id=6
and I want the quiz_id = 6 so that I can use this afterward to access data in the backend.
I am using Functional components if that helps.
You can take a look at axios's documentation in github
If what you want to do is a GET request this should be enough:
axios.get('http://localhost:3000/attempt/?quiz_id=6')
.then((res) => {
// handle success
console.log(res);
})
Also you have available this kind of usage:
axios.get('http://localhost:3000/attempt', {
params: {
quiz_id: 6
}
}).then((res) => {
// handle success
console.log(res);
});
You can use this too:
const data = await axios.get('http://localhost:3000/attempt/?quiz_id=6').then(res => res.data);
You can include dynamic quiz_id by using params. The way for this is to making an axios request using the id of the param that you want to update and return:
Your code will read like so:
axios.get('http://localhost:3000/attempt/${quiz_id}', quiz_id);

Django and Javascript: Take Info From API And Save To Database

I'm very new to Javascript with Django and I'm looking for some basic info on how to take info from an API that has already been returned, and post it to the database. I have used views.py to take information and save it to the database, but I haven't done this with info from an API that is achieved in Javascript. My project is a weather app that gets info from OpenWeather for a city that the user types into a box, and that part works - the API information is returned. I currently have a model for each Location, I just don't know how to save it in the database.
Is this done through fetch, using POST? I am also slightly confused about how the urls would be setup. Any information, maybe some sample github code, could help :)
For example, if I want to get the location and then add it to my 'favorites' would something like this make sense? I know I would still need to make the view, and url.
const location_content = document.querySelector('#content').value;
function add_to_fav() {
fetch('/favorites', {
method: 'POST',
body: JSON.stringify({
location_content: location_content
})
})
.then(response => response.json())
.then(result => {
console.log(result);
});
localStorage.clear();
return false;
}
Here is my model for each city that is returned via the API:
class Location(models.Model):
city = models.CharField(max_length=500)

Receive raw response data using axios

I am trying to receive the raw response data, not the response headers or body. As an example, an image here shows the tab where this data is found:
Now, I am trying to receive this data when making an HTTP Request using `Axios`. Is this even possible?
I have tried searching online for about 2 hours, as this was a huge problem I was facing. I tried other sites, including stack overflow, to get the correct answer. If possible, could you please answer my question if you know? Thanks in advance.
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?user=username&passwd=password'
function axiosTest() {
return axios.post(url).then((r) => {
console.log(r)
})
}
I'm pretty sure you must access the data property in the response object r. Also - since you are using the reddit API - make sure you are providing api_type in the request url (api_type=json for instance):
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?api_type=json&user=username&passwd=password'
function axiosTest() {
return axios.post(url).then((r) => {
console.log(r.data)
return r.data;
})
}
For anyone reading this: Just to clarify, the api_type parameter in the request url is specific to the reddit API and most likely won't work any other API.

Passing parameter to a GET request to retrieve specific information

I am trying to retrieve (GET) specific information based on a parameter that is passed. My code looks like this:
In index.js:
export var comments = (userId) => {
return new Promise((value) => {
axios.get('http://localhost:1000/getreviews/:userId')
.then((response) => {
console.log(response.data.comment);
})
})
}
In routes.js:
router.route('/:userId').get((req, res) => {
Users.find({user: req.params.userId})
.then((reviews) => res.json(reviews)
);
});
So I want to get relevant information. To give a higher-level idea of what is going on--there are multiple modals, and when a specific one is clicked I want to get specific information from the database, instead of getting all the information from the database and then do the extraction of relevant information in index.js based on the user's id. That way, I will be getting all the information on every modal click which is not efficient so I want to avoid it.
What is the problem exactly, is Users.find({user: req.params.id}) not returning the expected value? mongoose has findById which queries the db looking for the object with that specific id, in your case :
Users.findById(req.params.userId)
.then((reviews) => res.json(reviews)
);
edit: it seems like you're passing undefined as a parameter find, note that the name of the variable that is stored in params must be the same as the parameter you provided in your get method which is userId, so use req.params.userId instead.
edit2: js part
export var comments = (userId) => {
return axios.get(`http://localhost:1000/getreviews/${userId}`)
.then((response) => {
return response.data
})
}
Writing the GET request in a different way solved the issue:
axios({
method: 'get',
url: 'http://localhost:1000/getreviews/',
params: {
user: userId
})
Then I could access the userId in routes.js through req.query.user and it will give me the userId I just passed.

Categories