Api call: Call for key & value to a list and then Loop for value in another API call - json

i used Canvas api to call for information such as user ID, log in and log out time...but the APIs can only call for one user at a time, so i made this code to first call for a list of user IDs:
import requests
import json
def get_all_time_entries():
url_address = "mywebsite.com/api/v1/courses/1111/users?per_page=50"
headers = {"Authorization": "Bearer " + "this is my bearer"
}
all_time_entries = []
for page in range(1,15):
url = "mywebsite.com/api/v1/courses/1111/users?per_page=50&page="+str(page)
response = requests.get(url=url, headers=headers).json()
all_time_entries.append(response)
return all_time_entries
print(get_all_time_entries())
I've managed to call for a list of users like this:
{
"created_at": "time",
"email": "email",
"id": ID number, (***)
"integration_id": null,
"login_id": "email",
"name": "Name",
"short_name": "Name ",
"sis_import_id": 111,
"sis_user_id": "Name ",
"sortable_name": ", Name "
},
Now i want to use a new loop to call for API with this link: mywebsite.com/api/v1/audit/authentication/users/:user_id (:user_id are the IDs got in the last api call of mine, marked with (***)) and get all the information to a list. How should i use loop with all those IDs?

i've managed to find a solution for calling next APIs based on the value i got from the previous list with this code:
import requests
import json
def get_all_time_entries():
url = "mywebsite.com/api/v1/courses/1111/users?per_page=50"
headers = {
"Authorization": "Bearer " + "this is my bearer",}
uri = "mywebsite.com/api/v1/audit/authentication/users/"
result = []
all_time_entries = []
# loop through all pages and return list of users of certain pages
for page in range(1,15):
url = "mywebsite.com/api/v1/courses/1111/users?per_page=50&page="+str(page)
response = requests.get(url=url, headers=headers).json()
all_time_entries.append(response)
return all_time_entries
# Search for id value in all_time_entries
value = [res['id'] for res in all_time_entries]
# Loop through user log in api call by 'id'
for x in value:
url = "mywebsite.com/api/v1/audit/authentication/users/"+str(x)
callback = requests.get(url=url, headers=headers).json()
result.append(callback)
return result
print(get_all_time_entries())
Now the problem is this code keeps returning the value of the "all_time_entries" not the "result" one. i've also tried to add a certain value for the list "all_time_entries" (with no loops and calls):
all_time_entries = [{'id': 11, 'name': 'name', 'created_at': '2021-01-23T22:34:30+07:00', 'sortable_name': ', name', 'short_name': 'name', 'sis_user_id': 'name#email.com', 'integration_id': None, 'sis_import_id': 1, 'login_id': 'name#email.com', 'email': 'name#email.com'}, {'id': 22, 'name': 'name2', 'created_at': '2021-01-23T22:34:19+07:00', 'sortable_name': ', name2', 'short_name': 'name2', 'sis_user_id': 'name2#email.com', 'integration_id': None, 'sis_import_id': 1, 'login_id': 'name2#email.com', 'email': 'name2#email.com'}]
...and it worked
So i dont know if this method cannot work with a very long list or something, and is there a way to work with long list?

Related

DART - Filter JSON Data

I'm trying to filter the json data. There is a field called "brand" in my json (so basically I'm trying to filter the data by brands)
This is how my json looks
{
"items": [
{
"_id": "30baa1ca-4186-4ff0-abe8-a5970e753444",
"_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
"_createdDate": "2022-05-09T08:47:29.137Z",
"discountedPrice": "44.97",
"_updatedDate": "2022-05-09T08:48:44.147Z",
"getDealLink": "https://amzn.to/3FqBq4O",
"brands": [
"Amazon"
],
"title": "Mellanni Extra Deep Pocket Twin XL Sheet Set ",
"amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
"save": "#1 Best Seller",
"link-items-all": "/items/",
"link-items-title": "/items/mellanni-extra-deep-pocket-twin-xl-sheet-set-"
},
{
"_id": "a7d3aaa8-9654-4535-b6c5-b147ff0d8eb3",
"_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
"_createdDate": "2022-05-08T22:35:38.398Z",
"discountedPrice": "$81.59",
"_updatedDate": "2022-05-08T22:39:52.801Z",
"getDealLink": "https://amzn.to/3ymXGLe",
"brands": [
"Amazon"
],
"originalPrice": "$199.99",
"title": "2 Pack Stadium chairs for bleachers with back support",
"amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
"link-items-all": "/items/",
"link-items-title": "/items/2-pack-stadium-chairs-for-bleachers-with-back-support"
},
and this is my dart code
void getAmazon() async {
var response = await http.get(Uri.parse(url));
var decodeResponse = jsonDecode(response.body);
List data = decodeResponse['items'] as List;
Iterable filteredData = data.where((element) => element['brands'][0] == 'Amazon');
print(filteredData); // returns nothing
}
it doesn't return/print anything. What am I doing wrong?
Better to use contains to check if a brand is listed. Also check if "brands" field is available for better stability.
final filteredData = data.where((element) => (element['brands'] != null ? element['brands'].contains('Amazon') : false));
In your code, you are checking if brands it's equal to Amazon, but brands is actually a List. (Or in the case you are checking on a particular index, this could change)
So ["Amazon"] ≠ Amazon.
In the code below you will now check if brands contains "Amazon".
Iterable filteredData = data.where((element) => element['brands'].contains('Amazon'));
void getAmazon() async {
var response = await http.get(Uri.parse('https://mockbin.org/bin/e123b53d-6e35-49e7-a94e-f49554a63d7e'));
var decodeResponse = jsonDecode(response.body);
List data = decodeResponse['items'] as List;
Iterable filteredData = data.where((element) => element['brands'][0] == 'Amazon');
log('ddf ${filteredData}'); // returns nothing
}
I had added third product as brand from flipkart it filter this!
you can check this url https://mockbin.org/bin/e123b53d-6e35-49e7-a94e-f49554a63d7e
Your code actually works as expected!!!
[log] ddf ({_id: 30baa1ca-4186-4ff0-abe8-a5970e753444, _owner: 1d3480e5-0eda-47ef-8406-38d89bf15ded, _createdDate: 2022-05-09T08:47:29.137Z, discountedPrice: 44.97, _updatedDate: 2022-05-09T08:48:44.147Z, getDealLink: https://amzn.to/3FqBq4O, brands: [Amazon], title: Mellanni Extra Deep Pocket Twin XL Sheet Set , amazonlogo: wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346, save: #1 Best Seller, link-items-all: /items/, link-items-title: /items/mellanni-extra-deep-pocket-twin-xl-sheet-set-}, {_id: a7d3aaa8-9654-4535-b6c5-b147ff0d8eb3, _owner: 1d3480e5-0eda-47ef-8406-38d89bf15ded, _createdDate: 2022-05-08T22:35:38.398Z, discountedPrice: $81.59, _updatedDate: 2022-05-08T22:39:52.801Z, getDealLink: https://amzn.to/3ymXGLe, brands: [Amazon], originalPrice: $199.99, title: 2 Pack Stadium chairs for bleachers with back support, amazonlogo: wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346, link-items-all: /items/, link-items-title: /items/2-pack-stadium-chairs-for-bleachers-with-back-support})

How to retrive children from a single object intead of array in json-server?

I am using json-server for mock-backend to retrive children form a single object.
The parent table sentinel and the child table sensor
As you can see the sensors is an array and sentinel is an object.
I have used http://localhost:3000/sentinel?_embed=sensors but the response is not what i am expecting, because I want sensors: [{id: 1}, {id: 2}, ecc]
The official documentation shows that are two ways to retrive two tables:
_embed (include children) and _expand (include parent).
How could I achive this result?
Given that sentinel is a single object in your db.json and you can't have more than one sentinel it is not clear to me how your query is different from retrieving all sensors with sentinelId=10:
/sensors?sentinelId=10
In fact if you try this API:
/sentinel/10/sensors
it will work, because json-server rewrite the url exactly to the previous query.
If for some reason you don't want to use the sentinel id directly in the query, the other option is to use json-server as a module and define a custom route with the logic you need. Here's a basic example that exposes a /sentinel/sensors API and retrieve sentinel data along with the sensors whose sentinelId equals to the current sentinel id:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const db = router.db;
server.use(jsonServer.bodyParser);
server.get('/sentinel/sensors', (req, res) => {
const sentinel = db.get('sentinel').value();
const sensors = db
.get('sensors')
.filter({ sentinelId: sentinel.id })
.value();
res.send({ ...sentinel, sensors: sensors });
});
server.use(router);
server.listen(3001, () => {
console.log('Mock server is running on port ' + 3001);
});
That would give you a response like this:
{
"id": 10,
"name": "Sentinel",
"sensors": [
{
"id": 1,
"sentinelId": 10
},
{
"id": 2,
"sentinelId": 10
}
]
}
Here's a stackblitz

Flask Oauth2 get Google+ profile-picture-url from the profile-picture-json

I have a problem here in obtaining the Google+ profile-picture-url from the profile-picture-json. I'm quite a beginner and this is my first webapp so please take this into account.
My callback function:
def callback(self):
self.validate_oauth2callback()
oauth_session = self.service.get_auth_session(
data={'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': self.get_callback_url()
},
decoder=jsondecoder
)
me = oauth_session.get('').json()
social_id = 'google$' + me['sub']
username = me.get('name', None) if me.get('name', None) else me['email'].split('#')[0]
email = me['email'] if me['email_verified'] == True else None
url = me.get('profile', None)
image_json = 'https://www.googleapis.com/plus/v1/people/' + me['sub'] + '?fields=image&key=AIz..yAl..juCqj..sjj9y..PuM..R..9..F8p..mo'
image = image_json['image'] # <-- THIS DOESN'T WORK
return social_id, username, email, url, image, me
My problem is that the variable image_json contains the following:
{
"image": {
"url": "https://lh6.googleusercontent.com/-f..i0..dl..Gc/AAAAAAAAAAI/AAAAAAAAABQ/iNw-IEz...o/photo.jpg?sz=50",
"isDefault": false
}
}
and I have to extract the profile-picture-url from that. A substring method doesn't work since in order to get that code I have to "run" the url saved in image_json.
What I need is something like image = image_json['image'] to retrieve the string:
"https://lh6.googleusercontent.com/-f..i0..dl..Gc/AAAAAAAAAAI/AAAAAAAAABQ/iNw-IEz...o/photo.jpg?sz=50"
and I would like to change that size in 256 instead of 50.
I have followed many posts but I didn't found a solution for this thing.
The view that will call this function is the following:
#auth.route('/callback/<provider>')
def oauth_callback(provider):
oauth = OAuthSignIn.get_provider(provider)
social_id, username, email, url, image, jsonme = oauth.callback()
if social_id is None:
flash('Authentication failed! Access to ' + provider + ' denied.')
return redirect(url_for('main.home'))
user = User.query.filter_by(email=email).first()
if not user:
user = User(social_id=social_id, username=username, email=email, social_page=url, social_image=image)
db.session.add(user)
db.session.commit()
else:
...
login_user(user, True)
return redirect(url_for('main.home'))

Dartlang: How to get key and values from json?

I'm having a little problem and couldn't figure it out. I created a table with checkbox and it's working and can save to json without a problem. Now i wanna make my checkboxes have their default values set from json data when the page loads (to make it easier to edit). Anyway here is my code:
//row index
var index = 0;
//gets full info of student
var responseStudent = rpc.call('db.findOne', ['StudentAnket', {
'_id': '${this.objId}'
}]);
result = responseStudent['result'];
//gets info needed for my table
//{anket: true, request: true, statement: false, etc...}
var resultMat = result['listmaterial'];
//materials is a list which contains id, name of rows
materials.forEach((m) {
//creating table body
index = index + 1;
tbody.append(new Element.tr()
..append(new TableCellElement()..text = index.toString())
..append(new TableCellElement()..append(new LabelElement()
..text = m['name']
..setAttribute('for', m['id'])))
..append(new TableCellElement()..append(new InputElement()
..id = m['id']
..type = "checkbox"
..checked = "VALUE TAKEN FROM JSON")));
});
So how can i get keys and values from resultMat and set checked property for each checkbox?
Edit:
List materials = [{
'id': 'anket',
'name': 'Student anket'
}, {
'id': 'request',
'name': 'Request'
}, {
'id': 'statement',
'name': 'Statement'
}, {
'id': 'marklist',
'name': 'Mark List'
}];
Your information how your materials structure looks like is not clear. A List has only one value not two ('id, 'name of rows'). First you have to ensure that your JSON is not a String but a Dart data structure (Lists, Maps, values).
You can take a look at the answers to this questions to learn how this works
Dart Parse JSON into Table
Then you should be able to access the value like
..checked = resultMat[m['id']] ;

Sending grouped json data with ajax

I'm using extJS version 4.0 to generate a entry form. On that form there is a save button that sends all the fielddata to php via ajax. As transfer protocol for the data itself I'm using json.
As I need to make a dynamical (general) routine for processing this data (as that one form won't be the only form in that project) I would need that json data grouped somehow. One of the requirements I have is that I need the "fieldnames" to be as they are (as I use the fieldnames I get transmitted to me to access the approopriate coloumns in the database in the automatic save routine).
My question here is is there any way to somehow group the data that is transmitted via json (thus that extJS groups it).
As a simplified example:
On the entryform I'm saving data for 2 tables (1. Person 2. bankaccount) which have the following fields shown on the form:
-firstname
-lastname
for person
and
-account number
-bank number
for bankaccount
(the stores are accordingly)
Is there a way with extJS to group this data acordingly, thus generate something like this?
{"person":[{"firstname": "Mark", "lastname":"Smith"}],"bankaccount":[{"account number":123112,"bank number":1A22A1}]}
Currently I'm getting something like this:
{"firstname": "Mark", "lastname":"Smith","account number":123112,"bank number":1A22A1}
Both person and bankaccount are in their separate stores.
Tnx.
Well, you've two stores: one for 'person' and one for 'bankaccount'.
Ext.define ('Person', {
extend: 'Ext.data.Model' ,
fields: ['firstname', 'lastname']
});
Ext.define ('BankAccount', {
extend: 'Ext.data.Model' ,
fields: ['accountnumber', 'banknumber']
});
var personStore = Ext.create ('Ext.data.Store', {
model: 'Person' ,
data: [
{firstname: 'foo', lastname: 'bar'} ,
{firstname: 'zoo', lastname: 'zar'} ,
{firstname: 'too', lastname: 'tar'} ,
{firstname: 'goo', lastname: 'gar'} ,
{firstname: 'moo', lastname: 'mar'}
]
});
var bankAccountStore = Ext.create ('Ext.data.Store', {
model: 'BankAccount' ,
data: [
{accountnumber: 10000, banknumber: 10000} ,
{accountnumber: 20000, banknumber: 20000} ,
{accountnumber: 30000, banknumber: 30000} ,
{accountnumber: 40000, banknumber: 40000} ,
{accountnumber: 50000, banknumber: 50000}
]
});
Then, you want to dump these stores as JSON. No problem!
Make a container (jsonData) and then fill it up with your stores:
var jsonData = {
person: [] ,
bankaccount: []
};
personStore.each (function (person) {
jsonData.person.push (person.data);
});
bankAccountStore.each (function (bank) {
jsonData.bankaccount.push (bank.data);
});
console.log (Ext.JSON.encode (jsonData));
And this is the output on the console:
{"person":[{"firstname":"foo","lastname":"bar"},{"firstname":"zoo","lastname":"zar"},{"firstname":"too","lastname":"tar"},{"firstname":"goo","lastname":"gar"},{"firstname":"moo","lastname":"mar"}],"bankaccount":[{"accountnumber":10000,"banknumber":10000},{"accountnumber":20000,"banknumber":20000},{"accountnumber":30000,"banknumber":30000},{"accountnumber":40000,"banknumber":40000},{"accountnumber":50000,"banknumber":50000}]}
Is that what you've requested?
Here's the fiddle