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)
Related
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.
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;`
I have attached the problem statement and all the things required that I need to do so if someone can help that how to write code for this as I have tried a lot to do this used many approaches. please help as this is important for me to complete and now I have just 1 day left .
Problem Statement
As a user of UPI feature of One Application, one must have the functionality of viewing the
transaction history of all transactions processed on the application as well as view the details of each transaction by clicking on the tile of each such transaction .I need to create the following screen –
• Transaction History Screen – The transaction history screen lists all the transactions of a user
on UPI ecosystem done via that application. The list of transactions is populated like a chat
screen (bottom to top) with the most recent transaction appearing at the bottom. Transactions
should be grouped by the dates of transaction a
I'm using a basic fetch to obtain data from the given url server url={https://dev.onebanc.ai/assignment.asmx} that queries the data from a database by giving input.
this is the fetch function I wrote to get the desired response. [![Response[
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId: 1, recipientId: 2 }),
};
fetch('https://dev.onebanc.ai/assignment.asmx', requestOptions)
.then(response => response.json())
.then(data => { console.log(data) })
I got an object where I keep track of several things that the user can fill out, delete, update, etc.
Now, when 'loading' such a project, I make an api call to my backend using axios to retrieve the specific data to send it back to the client. The api call looks like this:
axios.get(`/api/data/${this.$route.params.dataId}`)
.then((response) => {
//Why does this not work?
this.nestedObject = response.data.object
//This DOES work... Why?
this.nestedObject.recipes = response.data.object.recipes
this.nestedObject.cheffs= response.data.object.cheffs
})
.catch((err) => {
console.log("error retrieving data: ", err);
});
Whenever I just set this.nestedObject equal to the data that is coming from the server, it does not work. nestedObject is not updated with the new values. But when I set the individual entries in the object equal to the data that is coming from the server, it does work and nestedObject is updated appropriately. Why is that?
I am trying to create a web page where the user can type in a subreddit name and then the webpage returns data based on that webpage like the posts, or the name of the moderators etc..
I want to create a REST api in nodejs/express.
i have done a bit of research and i think i have to get the json data from the subreddit i want and then get the relevant data...
The part i am confused is how do i start? everything i see is got to do with python but i need to do it in nodejs.
Also wont the json keep changing format... for one subreddit it will be different to another subreddit
I feel like you should check if theres an API for Reddit. Then when the user types in a subreddit, you would issue a GET request from your express route. The GET request would get the information from the Reddit API and send it back to the front.
let express = require('express');
let app = express();
app.get('/api/subredditname', (req, res) => {
//make your api request here, returning a promise hopefully
//then send your data back
.then((data) => {
res.send(data).status(200);
})
.catch((err) => {
console.log(err);
});
};