Creating a customer in the sandbox I always receive a 500. Google Reseller API - google-reseller-api

I have authenticated my request and I'm trying to create a customer in the sandbox but I always receive a error 500.
This is the request:
self.cred = OAuth2Credentials(access_token = access_token, client_id = client_id,
client_secret = client_secret, refresh_token = refresh_token,
token_expiry = None, token_uri ="https://accounts.google.com/o/oauth2/token",
user_agent = None, id_token = None)
self.client = httplib2.Http()
self.cred.refresh(self.client)
self.client = self.cred.authorize(self.client)
payload = {
"kind": "reseller#customer",
"customerId": "example.com",
"customerDomain": "example.com",
"postalAddress": {
"kind": "customers#address",
"contactName": "John Doe",
"organizationName": "Example Inc",
"locality": "Mountain View",
"region": "California",
"postalCode": "94043",
"countryCode": "US",
"addressLine1": "1600 Amphitheatre Parkway",
"addressLine2": "Mountain View",
"addressLine3": "California"
},
"phoneNumber": "+1 650-253-0000",
"alternateEmail": "alternateEmail#google.com"
}
paytext = json.dumps(payload)
da = self.client.request(method = 'POST', uri = "https://www.googleapis.com/apps/reseller/v1sandbox/customers/", body =paytext)
This is the error:
({'status': '500', 'content-length': '52', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'expires': 'Thu, 21 Feb 2013 11:09:51 GMT', 'server': 'GSE', '-content-encoding': 'gzip', 'cache-control': 'private, max-age=0', 'date': 'Thu, 21 Feb 2013 11:09:51 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json; charset=UTF-8'}, '{\n "error": {\n "code": 500,\n "message": null\n }\n}\n')
Is there any other way to do this?
Edit:
I've also tried with the discovery:
from apiclient.discovery import build
import httplib2
http = httplib2.Http()
from oauth2client.client import OAuth2Credentials
cred = OAuth2Credentials(access_token = access_token, client_id = client_id,
client_secret = client_secret, refresh_token = refresh_token,
token_expiry = None, token_uri ="https://accounts.google.com/o/oauth2/token" ,
user_agent = None, id_token = None)
client = httplib2.Http()
cred.refresh(client)
client = cred.authorize(client)
api = build(serviceName='reseller',version='v1sandbox',http=client)
api.customers().insert(body=payload).execute()
And there is an error too.

I believe your issue is related to this recent bug in the issue tracker.
http://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=3346

I think they've fixed their bug, though it doesn't appear to be marked as fixed. We were able to create a sandbox customer with. Here's the gist in Ruby:
def self.create
response = client.execute(
:api_method => service.customers.insert,
:body_object => {
:customerDomain => domain,
:alternateEmail => alternate_email,
:postalAddress => {
:contactName => contact_name,
:organizationName => organization_name,
:countryCode => two_letter_country_code,
:region => region,
:addressLine1 => street_address,
:locality => city,
:postalCode => zip
}
},
:authorization => authorization )
GoogleCustomer.new(response.data)
end
This seems to be the minimum information necessary to create a customer.
This assumes you've already handled the authorization. One thing to note: if you're using a service account you need to impersonate a user with access to create customers.

Related

Struggling with Validating the following Body Response in Postman

I have been trying to validate the following data from a body.
I have schema that validates the properties like Account ID and Associate number and that is fine, but what I want to drill down on the validation.
This below is the console and body response
From }) I get the below:
(1) [{,,,}] (not sure if those are commas or periods)
(0): [{,,,}]
AccountID: xxxx,
AssociateNumber: xxxx,
AssociateType: "Account",
AccountType: "PRIVATE AVIA",
DisplayName: "Jet Masters Air",
Body Response
[
{
"AccountID": xxxx,
"AssociateNumber": xxxx,
"AssociateType": "Account",
"AccountType": "PRIVATE AVIA",
"DisplayName": "Jet Masters Air",
}
]
//Im trying the following:
pm.test("Verify the Role name ", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.property.items.DisplayName).to.eql("Jet Masters Air")
})
Resolution:
pm.test("Verify the Role name ", function () {
var jsonData = pm.response.json(); pm.expect(jsonData[0].DisplayName).to.eql("Jet Masters Air") })

Parsing objects of a JSON for input validation

I want to use a database of valid ICAO and IATA airport codes for a discord bot input in typescript. However, I am not quite sure how to call the "icao" and "iata" contstructor of all objects, as each one is defined differently and there are thousands: e.g.:
"00AK": {
"icao": "00AK",
"iata": "",
"name": "Lowell Field",
"city": "Anchor Point",
"state": "Alaska",
"country": "US",
"elevation": 450,
"lat": 59.94919968,
"lon": -151.695999146,
"tz": "America\/Anchorage"
},
"00AL": {
"icao": "00AL",
"iata": "",
"name": "Epps Airpark",
"city": "Harvest",
"state": "Alabama",
"country": "US",
"elevation": 820,
"lat": 34.8647994995,
"lon": -86.7703018188,
"tz": "America\/Chicago"
},
The bot uses the following to provide the METAR of a specific airport:
name: 'metar',
description: 'Provides the METAR report of the requested airport',
category: CommandCategory.UTILS,
executor: async (msg) => {
const splitUp = msg.content.replace(/\.metar\s+/, ' ').split(' ');
if (splitUp.length <= 1) {
await msg.reply('please provide an ICAO airport code.');
return Promise.resolve();
}
const icaoArg = splitUp[1];
if (icaoArg.length !== 4) {
await msg.reply('please provide an ICAO airport code.');
return Promise.resolve();
}
request({
method: 'GET',
url: `https://avwx.rest/api/metar/${icaoArg}`,
headers: {
Authorization: process.env.METAR_TOKEN },
}, async (error, response, body) => {
const metarReport = JSON.parse(body);å
const metarEmbed = makeEmbed({
title: `METAR Report | ${metarReport.station}`,
description: makeLines([
'**Raw Report**',
metarReport.raw,
,
'**Basic Report:**',
`**Time Observed:** ${metarReport.time.dt}`,
`**Station:** ${metarReport.station}`,
`**Wind:** ${metarReport.wind_direction.repr} at ${metarReport.wind_speed.repr}kts`,
`**Visibility:** ${metarReport.visibility.repr}${metarReport.units.visibility}`,
`**Temperature:** ${metarReport.temperature.repr}C`,
`**Dew Point:** ${metarReport.dewpoint.repr}C`,
`**Altimeter:** ${metarReport.altimeter.value.toString()} ${metarReport.units.altimeter}`,
]),
fields: [
{
name: 'Unsure of how to read the raw report?',
value: 'Type \'**.metarhow**\' to learn how to read raw METARs',
inline: false
},
],
footer: { text: 'This METAR report may not accurately reflect the weather in the simulator. However, it will always be similar to the current conditions present in the sim.' },
});
await msg.channel.send({ embeds: [metarEmbed] });
});
},
};
Currently, if a user provides an ICAO that's not valid the bot crashes, or if they provide a valid IATA, the discord api throws the user an error to provide a valid ICAO code. How would I go about cross referencing the user argument with the JSON so the bot does not crash when inputting an invalid ICAO? Thanks

Why api response is comeing back with backslashes .How to avoid it

I have a category Table. I want to get all these data of the category table but the API response coming back with a backslash. How to avoid this backslash.
public function category_get($id = 0) {
$categories = $this->category_model->getRows($id);
// Check if the user data exists
if(!empty($categories)){
// Set the response and exit
//OK (200) being the HTTP response code
$this->response($categories, REST_Controller::HTTP_OK);
}else{
// Set the response and exit
//NOT_FOUND (404) being the HTTP response code
$this->response([
'status' => FALSE,
'message' => 'No category was found.'
], REST_Controller::HTTP_NOT_FOUND);
}
}
{
"category_id": "27",
"category_name": "Household",
"description": null,
"digital": null,
"banner": "category_27.jpg",
"data_brands": "",
"data_vendors": "",
"subcategories": "[{\"sub_id\":\"121\",\"sub_name\":\"DABUR RED AYURVEDIC TOOTHPASTE 100GM\",\"min\":50,\"max\":50,\"brands\":\"\"},{\"sub_id\":\"122\",\"sub_name\":\"Toilet Cleaner\",\"min\":82,\"max\":82,\"brands\":\"\"},{\"sub_id\":\"123\",\"sub_name\":\"Agarbatti & Puja Essentials \",\"min\":120,\"max\":120,\"brands\":\"\"},{\"sub_id\":\"135\",\"sub_name\":\"toothpaste\",\"min\":80,\"max\":80,\"brands\":\"\"},{\"sub_id\":\"144\",\"sub_name\":\"deo\",\"min\":0,\"max\":0,\"brands\":\"\"}]"
},

Struggling to get data from AWS lambda JSON

I'm working on a lambda project and getting data from an API inside the function which looks like this
{ "Title": "300", "Year": "2006", "Rated": "R", "Released": "09 Mar 2007", "Runtime": "117 min", "Genre": "Action, Fantasy, War", "Director": "Zack Snyder", "Writer": "Zack Snyder (screenplay), Kurt Johnstad (screenplay), Michael B. Gordon (screenplay), Frank Miller (graphic novel), Lynn Varley (graphic novel)", "Actors": "Gerard Butler, Lena Headey, Dominic West, David Wenham", "Plot": "King Leonidas of Sparta and a force of 300 men fight the Persians at Thermopylae in 480 B.C.", "Language": "English", "Country": "USA, Canada, Bulgaria", "Awards": "17 wins & 45 nominations.", "Poster": "https://m.media-amazon.com/images/M/MV5BMjc4OTc0ODgwNV5BMl5BanBnXkFtZTcwNjM1ODE0MQ##._V1_SX300.jpg", "Ratings": [ { "Source": "Internet Movie Database", "Value": "7.7/10" }, { "Source": "Rotten Tomatoes", "Value": "60%" }, { "Source": "Metacritic", "Value": "52/100" } ], "Metascore": "52", "imdbRating": "7.7", "imdbVotes": "691,774", "imdbID": "tt0416449", "Type": "movie", "DVD": "31 Jul 2007", "BoxOffice": "$210,500,000", "Production": "Warner Bros. Pictures", "Website": "http://300themovie.warnerbros.com/", "Response": "True" }
I've tried dot notation, indexing all sorts but no matter what I try, the console log just comes out with
2019-06-14T18:33:46.394Z ecc5d247-6475-464e-8dd7-bec310d98c4a INFO undefined
Has anyone else had the same issue before with lambda and lex?
Thanks
const https = require('https')
let url = "http://www.omdbapi.com/?t=300&r&apikey=3ecc35a"
let reply;
const http = require('http')
let test;
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log(body);
reply = JSON.parse(body);
});
});
This currently produces a perfectly good JSON in the console but it's impossible to actually extract anything. I've tried reply.Year, reply["Year"], reply.[0].Year almost any combination I can think off.
Full Code
'use strict';
'use fetch';
// Close dialog with the customer, reporting fulfillmentState of Failed or Fulfilled ("Thanks, your pizza will arrive in 20 minutes")
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}
// --------------- Events -----------------------
function dispatch(intentRequest, callback) {
console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
const sessionAttributes = intentRequest.sessionAttributes;
//const film = intentRequest.currentIntent.film;
const film = intentRequest.currentIntent.slots.film.toString();
console.log(intentRequest.currentIntent.slots.film.toString());
const https = require('https')
let url = "http://www.omdbapi.com/?t=300&r&apikey=3ecc35a"
let reply;
const http = require('http')
let test;
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log(body);
reply = JSON.parse(body);
});
});
//const rating = reply.imdbRating;
console.log(reply);
callback(close(sessionAttributes, 'Fulfilled',
{'contentType': 'PlainText', 'content': `The film ${film} has a rating of `}));
}
// --------------- Main handler -----------------------
// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
exports.handler = (event, context, callback) => {
try {
dispatch(event,
(response) => {
callback(null, response);
});
} catch (err) {
callback(err);
}
};
I tried to reproduce the issue with that code and got the following error
Response:
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'name' of undefined",
"trace": [
"TypeError: Cannot read property 'name' of undefined",
" at dispatch (/var/task/index.js:20:112)",
" at Runtime.exports.handler (/var/task/index.js:65:9)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:63:25)",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
Line 20 of index.js for me is:
console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
However when using the test event in the question event.currentIntent doesn't exist and the name property of the event object doesn't exist either.
If I remove part of the console.log statement and change it to reference the Title attribute which exists in the test event I get:
console.log(`request received for Title=${intentRequest.Title}`);
INFO request received for Title=300
Seems like the function's code is referencing attributes fine but the function's just not receiving it's expected event objects.
HTH
-James

Use API's URL to receive json

I am accessing the api of world weather online. I have configured the url and it is displayed below-
http://api.worldweatheronline.com/premium/v1/marine.ashx?key=XXXXXXXXXXXXXXXX&q=-34.48,150.92&format=json
Note: my API key is displayed as XXXXXXXXXXXX and this is returning the following:
{
"data": {
"request": [],
"weather": [
{
"date": "2016-11-20",
"astronomy": [],
"maxtempC": "27",
"maxtempF": "80",
"mintempC": "15",
"mintempF": "58",
"hourly": [
{
"time": "0",
"tempC": "15",
...
I want to GET this json in JS and then log the value of TempC.
How can this be done?
The simplest way would be using request. You can install it with npm install request
const request = require('request')
const apiKey = 'XXXXXXXX'
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx'
let qs = {
q: '-34.48,150.92',
format: 'json',
key: apiKey
}
request({ url, qs }, (err, response, body) => {
if (err)
return console.error(err)
if (response.statusCode != 200)
return console.error('status:', response.statusCode, body)
body = JSON.parse(body)
console.log(body.data.weather[0].hourly[0].tempC)
})