Yahoo Gemini API Python Example to fetch reports? - yahoo-api

https://developer.yahoo.com/gemini/
I need to download yahoo gemini ad reports. But yahoo documentation only has php code and no python. can someone please share any inputs ?
I have done oauth before but it had some basic documentation

Try this lib https://github.com/josuebrunel/yahoo-oauth with examples below
import urllib
import json
import time
from yahoo_oauth import OAuth2
oauth = OAuth2(None, None, from_file='credentials.json')
if not oauth.token_is_valid():
oauth.refresh_access_token()
# get all accounts
response = oauth.session.get("https://api.admanager.yahoo.com/v1/rest/advertiser/")
data = response.content
print data
jdata = json.loads(data)
for j in jdata['response']:
print "{} {}".format(j['id'], j['advertiserName'])
# get advertiser data
advertiser_id = 12345678
report_date_from = "2016-08-28"
report_date_to = "2016-08-28"
payload = {"cube": "performance_stats",
"fields": [
{"field": "Day"},
{"field": "Impressions"},
{"field": "Conversions"},
{"field": "Spend"},
{"field": "Campaign ID"}
],
"filters": [
{"field": "Advertiser ID", "operator": "=", "value": advertiser_id},
{"field": "Day", "operator": "between", "from": report_date_from, "to": report_date_to}
]}
response = oauth.session.post("https://api.admanager.yahoo.com/v1/rest/reports/custom?reportFormat=json", json=payload)
print response.content
jdata = json.loads(response.content)
job_id = jdata['response']['jobId']
# you will need to add some loop and waits before the report is ready
time.sleep(60)
url = "https://api.admanager.yahoo.com/v1/rest/reports/custom/{}?advertiserId={}".format(job_id, advertiser_id)
response = oauth.session.get(url)
print response.content
# report will be returned as url
rdata = json.loads(response.content)
if 'status' in rdata['response'] and rdata['response']['status'] == 'completed':
report = urllib.urlopen(rdata['response']['jobResponse']).read()
print report

Related

facebook messenger curl request returns <Response [400]>

I am new to the messenger API, I want to send a message using a curl post request, this is my code:
import requests
ACCESS_TOKEN = an Active access token
fb_url = "https://graph.facebook.com/v10.0/me/messages"
data = {
'recipient': '{"id":4098757906843152}',
"message": {
"text": "hello, world!"
},
"messaging_type": "MESSAGE_TAG",
"tag": "ACCOUNT_UPDATE"
}
params = {'access_token': ACCESS_TOKEN}
resp = requests.post(fb_url, params=params, data=data)
print(resp)
unfortunately, I got this message <Response [400]>
any help would be appreciated
You need to change data to json.
See https://stackoverflow.com/a/26344315/603756
Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call
import requests
ACCESS_TOKEN = '<access_token>'
fb_url = 'https://graph.facebook.com/v10.0/me/messages'
data = {
'recipient': '{"id":<psid>}',
"message": {
"text": "hello, world!"
}
}
params = {'access_token': ACCESS_TOKEN}
resp = requests.post(fb_url, json=data, params=params)
print(resp)

Having an issue with Dialogflow API WebhookResponse V2 for Actions for Google

I'm testing Actions for Google, so I created some simple Sinatra application which looks something like:
require 'sinatra'
require 'json'
post '/google_assistant_api' do
content_type :json
case intent_name
when "input_welcome"
decorated_response
when "Recipe name"
basic_card
end
end
private
def decorated_response
{
source: "test source",
speech: "speech",
display_text: "something"
}.to_json
end
def intent_name
parsed_request["queryResult"]["intent"]["displayName"]
end
def parsed_request
#parsed_request ||= JSON.parse(request.body.read)
end
def basic_card
{
"fulfillmentText": "ACTIONS_ON_GOOGLE",
"fulfillmentMessages": [
{
"platform": "PLATFORM_UNSPECIFIED",
"text": {
"text": [
"string text"
]
},
"image": {
"imageUri": "https://avatars3.githubusercontent.com/u/119195?
s=400&v=4"
},
"basicCard": {
"title": "title string",
"subtitle": "subtitle",
"formattedText": "formatted text",
"image": {
"imageUri": "https://avatars3.githubusercontent.com/u/119195"
},
"buttons": []
}
}
],
"source": "source string"
}.to_json
end
Please note that I'm using V2 of the API and testing using google assistant:
I tried many other response formats based on https://gist.github.com/manniru/f52af230669bd3ed2e69ffe4a76ab309 with no luck. I keep getting:
Sorry! there was no response from the Agent. Please try later.
Is there anyone who tried non nodejs response with luck? I would appreciate any sample response as the simple response seems to be working, however as for the basic card I'm having no luck.
Dialogflow's v2 API uses a different format for webhook requests and responses which is documented here:
Dialogflow v2 Webhook Request
Dialogflow v2 Webhook Response
It appears that your code is using the old format.

How to get code coverage percentage for latest build from TFS 2017u2 using PowerShell & REST API

Using PowerShell, how can I query Team Foundation Server 2017 Update 2 (on-premises) to get the code coverage percentage metric from the latest completed gated check-in?
I've not found a clear API call to use in the MS reference documentation. In the web interface, I can see in the dashboard for a given completed build the percentage value and a link to download the entire Visual Studio coverage file. I don't want the file, though. I just want to make an API call and get the percent coverage value for the last successful build of a given definition.
Unfortunately, the docs for VSTS's REST API are down right now, but this should get you started (pulled from Google's Cache).
This endpoint handles everything related to Tests and Code Coverage.
https://{instance}/DefaultCollection/{project}/_apis/test/codeCoverage?api-version={version}[&buildId={int}&flags={int}]
Provide values for the following and then run this Invoke-RestMethod to get the data back.
$Instance = 'fabrikam-fiber-inc.visualstudio.com' #your URL here
$ProjectName = #YourProjectNameHere
$buildID = #YourBuildIDHere
$version = '2.0-preview'
Invoke-RestMethod -uri https://$Instance/DefaultCollection/$ProjectName/_apis/test/codeCoverage?api-version=$version
Here's a sample response you can get back:
Status code: 200
{
"value": [
{
"configuration": {
"id": 51,
"flavor": "Debug",
"platform": "Any CPU",
"uri": "vstfs:///Build/Build/363",
"project": {}
},
"state": "0",
"lastError": "",
"modules": [
{
"blockCount": 2,
"blockData": "Aw==",
"name": "fabrikamunittests.dll",
"signature": "c27c5315-b4ec-3748-9751-2a20280c37d5",
"signatureAge": 1,
"statistics": {
"blocksCovered": 2,
"linesCovered": 4
},
"functions": []
}
],
"codeCoverageFileUrl": "..."
}
],
"count": 1
}
It looks like blocksCovered and livesCovered are probably the closest you'll get from the API. Let me know if you need some help or get stuck. Eventually, the docs will be back online at this URL.

How to validate response in Postman?

I am trying to validate response body including errors in postman. How can I validate the response and text below?
{
"responseHeader": {
"publisherId": "12345",
"responseId": "abbcb15d79d54f5dbc473e502e2242c4abbcb15d79d54f5dbc473e502e224264",
"errors": [
{
"errorCode": "1004",
"errorMessage": "XXXX Not Found"
}
]
}
}
These are my tests which are failing:
tests['response json contains responseHeader'] = _.has(responseJSON, 'responseHeader');
tests['response json contains errors'] = _.has(responseJSON, 'responseHeader.publisherId');
tests["Response has publisher id"] = responseJSON.publisherId === 10003;
In the "Test" tab, parse your response body into an object, then use JavaScript to perform your tests.
var data = JSON.parse(responseBody);
tests["publisherId is 12345"] = data.responseHeader.publisherId === "12345";
Take a look at the test examples at the Postman site:
https://www.getpostman.com/docs/postman/scripts/test_scripts
https://www.getpostman.com/docs/postman/scripts/test_examples

Pagination Links in Yii2 Rest API Custom Action Response

I have created my own object/index action in a yii rest controller which does some simple things:
public function actionIndex($name){
$query = Object::find();
$count = $query->count();
$pagination = new Pagination(['totalCount'=>$count]);
$objectList = $query->offset($pagination->offset)->limit($pagination->limit)->all();
return $objectList;
}
When I make a request to: http://localhost:8443/v0/objects?name=warehouse&page=1&per-page=1 I receive the following response:
[
{
"id": 2,
"data": {
"city": "Test",
"name": "ABC Warehouse",
"postal_code": "M1F 4F2",
"street_address": "1234 Street",
"owner": 76,
"created_at": "2016-09-23 15:10:20",
"updated_at": "2017-07-27 11:56:15",
"created_by": 9,
"updated_by": 13
},
"displayData": []
}
]
I would like to include the pagination link information as shown here but am not sure how to go about this
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
HTTP/1.1 200 OK
...
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self,
<http://localhost/users?page=2>; rel=next,
<http://localhost/users?page=50>; rel=last
I assume you're using the yii\rest\ActiveController
A quick look into the yii2 source suggests (to me) that whatever is returned need to implement the yii\data\DataProviderInterface. Right now your code does not return the Pagination object at all to be handled.
Assuming you're Object extends ActiveRecord, try this in your action...
public function actionIndex($name){
$query = Object::find(); // Assumes Object extends ActiveRecord
$countQuery = clone $query; // Good idea to clone query
$count = $countQuery->count();
$pagination = new Pagination(['totalCount'=>$count]);
$query->offset($pagination->offset)->limit($pagination->limit);
return new ActiveDataProvider([
'query' => $query,
'pagination' => $pagination,
]);
}
Note, this code is NOT tested. Hopefully it will help anyway.
--- Edit ---
Also in the yii\rest\ActiveController set this property (as suggested by Scott)
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];