Adding multiple users JSON for Google Directory API (Python) - google-admin-sdk

When I try to add users:
In this way I can only add one user, but I will need to add multiple users from the JSON file.
req = [
{
"primaryEmail": "first.user#mydomain.com",
"name": {
"givenName": "UserName",
"familyName": "UserLastName"
},
"suspended": False,
"password": "my password",
"hashFunction": "SHA-1",
"changePasswordAtNextLogin": False,
"agreedToTerms": True,
"ipWhitelisted": False
},
{
"primaryEmail": "second.user#exnesstest.com",
"name": {
"givenName": "FirstName",
"familyName": "LastName"
},
"suspended": False,
"password": "my password",
"hashFunction": "SHA-1",
"changePasswordAtNextLogin": False,
"agreedToTerms": True,
"ipWhitelisted": False
}
]
users = service.users().insert(body=req).execute()
I get some error like:
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://admin.googleapis.com/admin/directory/v1/users?alt=json returned "Invalid Input: primary_user_email">
How can I add multiple users in this way?

You would have to use a BatchRequest if you want to send multiple actions in one API call. Here is an example from the Python documentation provided by google
def list_animals(request_id, response, exception):
if exception is not None:
# Do something with the exception
pass
else:
# Do something with the response
pass
def list_farmers(request_id, response):
"""Do something with the farmers list response."""
pass
service = build('farm', 'v2')
batch = service.new_batch_http_request()
batch.add(service.animals().list(), callback=list_animals)
batch.add(service.farmers().list(), callback=list_farmers)
batch.execute()
You can read more about the method here : https://developers.google.com/admin-sdk/directory/v1/guides/batch
Or use the github repository directly (where the example came from): https://googleapis.github.io/google-api-python-client/docs/batch.html
The only thing you need to be aware of is the threshold of requests send per second/minute/hour , but google would error out if you exceed the limit and you would have to limit the requests using an Exponential Backoff

Related

Amazon SP-API Listings API putListingsItem How To Update price and quantity? Node.js

I am using amazon-sp-api (JavaScript client for the Amazon Selling Partner API) but this is not limited to this client. All I want to do is use the Amazon SP-API Listings API's putListingsItem call to update the price and quantity of an item I have listed.
productType
According to the ListingsItemPutRequest docs, productType and attributes are required for this call.
Firstly, to obtain the correct productType value, you are supposed to search for a product definitions type using the Product Type Definitions API. So, I do that, and call searchDefinitionsProductTypes, just to discover my product has no matching product type.
Ultimately, I gave the value PRODUCT for productType field. Using PRODUCT, I made the getDefinitionsProductType call and got an object containing an array of propertyNames, shown below:
"propertyNames": [
"skip_offer",
"fulfillment_availability",
"map_policy",
"purchasable_offer",
"condition_type",
"condition_note",
"list_price",
"product_tax_code",
"merchant_release_date",
"merchant_shipping_group",
"max_order_quantity",
"gift_options",
"main_offer_image_locator",
"other_offer_image_locator_1",
"other_offer_image_locator_2",
"other_offer_image_locator_3",
"other_offer_image_locator_4",
"other_offer_image_locator_5"
]
},
On seeing this, I decide list_price and fulfillment_availability must be the price and quantity and then try using these in my code below.
attributes
The attributes value is also required. However, their current docs show no clear example of what to put for these values, which are where I must put price and quantity somewhere.
I found this link about patchListingsItem and tried to implement that below but got an error.
code:
// trying to update quantity... failed.
a.response = await a.sellingPartner.callAPI({
operation:'putListingsItem',
path:{
sellerId: process.env.SELLER_ID,
sku: `XXXXXXXXXXXX`
},
query: {
marketplaceIds: [ `ATVPDKIKX0DER` ]
},
body: {
"productType": `PRODUCT`
"requirements": "LISTING_OFFER_ONLY",
"attributes": {
"fulfillment_availability": {
"fulfillment_channel_code": "AMAZON_NA",
"quantity": 4,
"marketplace_id": "ATVPDKIKX0DER"
}
}
});
console.log( `a.response: `, a.response )
error:
{
"sku": "XXXXXXXXXXXX",
"status": "INVALID",
"submissionId": "34e1XXXXXXXXXXXXXXXXXXXX",
"issues": [
{
"code": "4000001",
"message": "The provided value for 'fulfillment_availability' is invalid.",
"severity": "ERROR",
"attributeName": "fulfillment_availability"
}
]
}
I also tried using list_price :
// list_price attempt... failed.
a.response = await a.sellingPartner.callAPI({
operation:'putListingsItem',
path:{
sellerId: process.env.SELLER_ID,
sku: `XXXXXXXXXXXX`
},
query: {
marketplaceIds: [ `ATVPDKIKX0DER` ]
},
body: {
"productType": `PRODUCT`
"requirements": "LISTING_OFFER_ONLY",
"attributes": {
"list_price": {
"Amount": 90,
"CurrencyCode": "USD"
}
});
console.log( `a.response: `, a.response )
Error (this time seems I got warmer... maybe?):
{
"sku": "XXXXXXXXXXXX",
"status": "INVALID",
"submissionId": "34e1XXXXXXXXXXXXXXXXXXXX",
"issues": [
{
"code": "4000001",
"message": "The provided value for 'list_price' is invalid.",
"severity": "ERROR",
"attributeName": "list_price"
}
]
}
How do you correctly specify the list_price or the quantity so this call will be successful?
Just tryin to update a single item's price and quantity.
The documentation for this side of things is terrible. I've managed to get some of it through a fair bit of trial and error though.
Fulfillment and Availability can be set with this block of JSON
"fulfillment_availability": [{
"fulfillment_channel_code": "DEFAULT",
"quantity": "9999",
"lead_time_to_ship_max_days": "5"
}]
and List price gets set, oddly, with this block. I'm still trying to find out how to set the List Price with Tax however.
"purchasable_offer": [{
"currency": "GBP",
"our_price": [{"schedule": [{"value_with_tax": 285.93}]}],
"marketplace_id": "A1F83G8C2ARO7P"
}]
Hope this helps you out :)

Amplify I can't get the Sub and other attributes of a user registered with oauth

I need to get attributes of a user when they log in with oauth. Currently Hub.listen returns me some user data like this:
{
"Session": null,
"authenticationFlowType": "USER_SRP_AUTH",
"client": {
"endpoint": "https://cognito-idp.us-east-1.amazonaws.com/",
"fetchOptions": [Object]
},
"keyPrefix": "CognitoIdentityServiceProvider.vifuv747v73gj48v",
"pool": {
"advancedSecurityDataCollectionFlag": true,
"client": [Client],
"clientId": "vifuv747v73gj48v",
"storage": [Function MemoryStorage],
"userPoolId": "us-east-1_gkfke8e",
"wrapRefreshSessionCallback": [Function anonymous]
},
"signInUserSession": {
"accessToken": [CognitoAccessToken],
"clockDrift": 0,
"idToken": [CognitoIdToken],
"refreshToken": [CognitoRefreshToken]
},
"storage": [Function MemoryStorage],
"userDataKey": "CognitoIdentityServiceProvider.sdfj656fs5efsdf45es.Google_0000000000000000000000.userData",
"username": "Google_0000000000000000000000"
}
Also I can't access them with: currentAuthenticatedUser()
const { attributes } = await Auth.currentAuthenticatedUser();
//attributes === undefined
When a user registers I have to perform certain tasks in the database, etc. Therefore I would like to know how to identify if the login by oauth created a new account to perform the necessary tasks. Or, failing that, to be able to access the sub for me to check if that user already existed and perform the tasks in case it is a new user
Found out how to access attributes when using Oauth to login:
const user = await Auth.currentAuthenticatedUser();
const attributes = user.signInUserSession?.idToken?.payload;
I noticed this adds some extra properties but it does what I need.

Facebook Messenger Webhook get "outbound" message text

I am getting the following back as a webhook (Message-Delivered Callback) but I need to get the actual content of the message that was delivered. The Message-Received Callback has a "text" field that contains this information, but this one does not.
{
"object": "page",
"entry": [{
"id": 2880130XXXX7538,
"time": 1462299418787,
"messaging": [{
"sender": {
"id": 1261XXXX3865793
},
"recipient": {
"id": 2880XXXX7977538
},
"delivery": {
"mids": ["mid.146XXXX412750:6bd62757XXXXd68848"],
"watermark": 1462XXXX12769,
"seq": 50
}
}]
}]
}
I have tried unsuccessfully to use graph api with the message id but the docs are a little unclear if this is possible (https://developers.facebook.com/docs/graph-api/reference/v2.6/message/)
The token I am using has the following permissions: read_page_mailboxes, manage_pages, pages_messaging.
Any help would be greatly appreciated!!
Add "m_" to your delivery mids, so in this case:
m_mid.146XXXX412750:6bd62757XXXXd68848
And then make a facebook-graph-api request using that as the "message-id" in the URL. Use fields=message to get the message text.
Reference:
https://developers.facebook.com/docs/graph-api/reference/v2.6/message/
You can try this code:
$M = $input['entry'][0]['messaging'][0]['message']['text'];
AND "$M" is what you want.
it's work! But i can't explain why

How to get the return data of a save with Ember Data?

I'm using Ember.js with ember-data to make a GUI for a self made API.
I've been following this tutorial to handle authentication but I want to use ember-data instead of custom jQuery requests.
One thing I have to do is to call the API to create a new session, by sending email and password, and the API sends me back an API Key object.
Here is my LoginController handling the loginUser action (it's CoffeeScript) :
App.LoginController = Ember.ObjectController.extend
actions:
loginUser: ->
session = #store.createRecord 'session',
email: #get 'email'
password: #get 'password'
session.save()
Here is the result I get when creating a session:
{
"users": [
{
"id": "525fa0286c696c0b14040000",
"email": "john.doe#mydomain.com",
"first_name": "John",
"surname": "Doe"
}
],
"api_key": {
"id": "526e464c6c696c07d2000000",
"type": "session",
"key": "6b824d6a-a065-4b6f-bb28-5c19389760f8",
"expires_at": "2013-10-28T11:41:08+00:00",
"user_id": "525fa0286c696c0b14040000"
}
}
I have Session, ApiKey and User models. I can create the session, but the thing I don't understand is how to access the return value of the save() method.
I know that my ApiKey and User are loaded somewhere because I get an error after save() if their respective Ember model don't exist but I don't know how to access them.
I've tried to use save() callbacks like then() or didCreate event but there's a lack of documentation about arguments passed to these callbacks and how to use them.
Ember.js 1.1.2
Ember Data 1.0.0.beta.3
EDIT:
I've tried to create an actuel Session model on my API, resulting in this JSON output:
{
"api_keys": [
{
"id": "526f69526c696c07d2110000",
"type": "session",
"key": "4c26af37-2b21-49c2-aef5-5850a396da0b",
"expires_at": "2013-10-29T08:22:50+00:00",
"user_id": "525fa0286c696c0b14040000"
}
],
"users": [
{
"id": "525fa0286c696c0b14040000",
"email": "john.doe#coreye.fr",
"first_name": "John",
"surname": "Doe"
}
],
"session": {
"id": "526f6e666c696c18c0010000",
"api_key_id": "526f69526c696c07d2110000"
}
}
(note the root element is now session)
It doesn't work better because now my save action leads to the following error (not in the console but then points to error callback):
Object function () { [...] } has no method 'eachTransformedAttribute'
I get this error, the relation between Session and ApiKey being declared in Ember Data models or not...
Your second example JSON looks better: since you are saving a Session, I would expect a session node in the response and other models to be side loaded. You can access the saved session after it's saved by using a promise callback:
session.save().then (savedSession) =>
console.log savedSession.api_key.key
Since you have _id relationship keys in your JSON, I assume you are using the ActiveModel adapter and its default serializer:
App.ApplicationAdapter = DS.ActiveModelAdapter.extend()

Is it possible to set the django-tastypie objects key?

By default, when using django-tastypie and fetching a resource list, the response is of the format:
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 3
},
"objects": [{
"body": "Welcome to my blog!",
"id": "1",
"pub_date": "2011-05-20T00:46:38",
"resource_uri": "/api/v1/entry/1/",
"slug": "first-post",
"title": "First Post",
"user": "/api/v1/user/1/"
},
...
]
}
I've dug into the documentation and looked & looked, but I can't seem to find any kind of meta option or setting to change the "objects" key to actually describe the returned items. For example, let's say I have list of locations in one api call and a list of people in another. I'd like to be able to differentiate the key to "locations" and "people". The real reason for this is because I'm using RestKit on iOS and want to be able to set up multiple mappings.
The Resource hooks alter_* can be used to alter the structure of the data.
An example Resource using 'locations' would be:
class MyLocationsResource(ModelResource):
def alter_list_data_to_serialize(self, request, data):
data['locations'] = data['objects']
del data['objects']
return data
def alter_deserialized_list_data(self, request, data):
data['objects'] = data['locations']
del data['locations']
return data