How to download facebook report using Insights API Asynchronous Jobs? - facebook-graph-api

Hi I'am new to facebook marketing API. I want to download account complete report in csv format for which I am using Insights API Asynchronous Jobs , Using which I am able to get "report_run_id" and after that I made api request for this link .Its giving wrong response. Can anybody help me how can download report in csv format.code which i tried is:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.facebook.com/ads/ads_insights/export_report/?report_run_id=279445242544715&name=reports&format=csv")
.get()
.build();
Response response = client.newCall(request).execute();
if(response.isSuccessful()){
String resposes=response.body().string();
}

I'll give examples using curl, but you should be able to translate these to javascript easily.
Using the report_run_id, you can query the completeness of the async query, for example:
curl -G \
-d 'access_token=<ACCESS_TOKEN>' \
https://graph.facebook.com/v2.10/1000002
This should eventually give you a completion of 100%:
{
"id": "6044775548468",
"account_id": "1010035716096012",
"time_ref": 1459788928,
"time_completed": 1459788990,
"async_status": "Job Completed",
"async_percent_completion": 100
}
You then need to query the report_run_id for with the insights edge:
curl -G \
-d 'access_token=<ACCESS_TOKEN>' \
https://graph.facebook.com/v2.10/<YOUR_REPORT_RUN_ID>/insights

Related

Authenticating API Call to Google ML Engine with an API Key

I have a saved model in Google AI Platform that works when I test the predictions in the AI Platform UI.
However, when I try and access the API via REST, I keep getting a response with a 401 status. I would like to know how to do this successfully.
My api URL looks like the following:
'https://ml.googleapis.com/v1/projects/ml-project-name/models/my-model-names/versions/v2:predict
I would like to be able to access this endpoint in an external app that's residing on any platform to generate predictions with it.
Google Cloud recommends service account authorization, however, all of the directions for it require setting environment variables so the app can automatically authenticate you. I'd prefer to supply them directly in the request to make things more portable and congruent with how it's done elsewhere at work.
So instead I tried getting an API key.
According to this page: https://cloud.google.com/docs/authentication/api-keys you can authenticate a request in the following way:
POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
However, when I run the following code, my request status is 401:
import requests
api_key = my_sample_api_key
url = f'https://ml.googleapis.com/v1/projects/project-name/models/model-name/versions/v2:predict?key={api_key}'
json = {"instances": [ {"input_1": ["Please predict this text"]}]}
res = request.post(url, json=json)
Any help would be appreciated, thank you.
Auto ML does not support the use of API keys when sending requests. I suggest to use the auth token on your request or use the available client libraries to send predictions.
Here is a code snippet using its python client library for sending prediction request:
# Create the AI Platform service object.
# To authenticate set the environment variable
# GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
service = googleapiclient.discovery.build('ml', 'v1')
def predict_json(project, model, instances, version=None):
"""Send json data to a deployed model for prediction.
Args:
project (str): project where the AI Platform Model is deployed.
model (str): model name.
instances ([Mapping[str: Any]]): Keys should be the names of Tensors
your deployed model expects as inputs. Values should be datatypes
convertible to Tensors, or (potentially nested) lists of datatypes
convertible to tensors.
version: str, version of the model to target.
Returns:
Mapping[str: any]: dictionary of prediction results defined by the
model.
"""
name = 'projects/{}/models/{}'.format(project, model)
if version is not None:
name += '/versions/{}'.format(version)
response = service.projects().predict(
name=name,
body={'instances': instances}
).execute()
if 'error' in response:
raise RuntimeError(response['error'])
return response['predictions']
Here is a sample of sending a POST request using curl with the auth token:
curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d #request.json \
https://ml.googleapis.com/v1/projects/your-project/models/you-model-name/versions/your-version-name:predict

Unable to query through elasticsearch

I am using Elasticsearch in my Django application. When i try to query my result using curl i get found = false. Can someone help me here !]1
I am following this tutorial and my code when i execute https://www.freecodecamp.org/news/elasticsearch-with-django-the-easy-way-909375bc16cb/ and my code fails when i execute
curl -XGET 'localhost:9200/blogpost-index/blog_post_index/1?pretty'
The above method is for fetching the document by its id. As per the JSON response of the ES server, document with id 4 doesn't exist. You can possibly try to fetch all documents by using match_all query on the index to fetch all the documents and see if the document you are trying to see exists.
Here's the CURL syntax:
curl -X GET "localhost:9200/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}
}
'
Reference : Match All Query
You can also see the range of documents IDs to see if the document you are trying to fetch, exists.
Range Filter for IDs

Querying Couchbase Bucket from Postman - Unrecognized parameter in request

Using the Postman tool, I'm trying to query a Couchbase bucket. I'm getting an error response 1065 that there is an "unrecognized parameter in request". The query will work fine within the Couchbase workbench, but I need to be able to do this from Postman.
I'm making a POST request with this body:
{
"statement" : "SELECT * from `myBucketName` where id = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee""
}
There error message is:
"msg": "Unrecognized parameter in request: {\n\"statement\" : \"SELECT from `myBuckeyName` where _id "
I think this is just an issue with how my request body is formatted, I'm just new to this and not sure how it should be formatted based off the error I'm getting.
Here's how I did it:
Open Postman
Select POST
Use a URL of http://localhost:8093/query/service
Under "Authorization", use Basic Auth (with the username/password you've created for Couchbase)
Under "Body", select "x-www-form-urlencoded"
Add a KEY of statement and a value of your query
Click SEND
I got a 200 OK response with the results of the query. Screenshot:
You should definitely check out the Couchbase REST API documentation. It uses curl instead of Postman, but that's a translation you'll eventually get used to.

Graphene Django "Must provide query string"

I have setup a Graphene server using Django. When I run my queries through GraphiQL (the web client), everything works fine. However, when I run from anywhere else, I get the error: "Must provide query string."
I did some troubleshooting. GraphiQL sends POST data to the GraphQL server with Content-Type: application/json. Here is the body of the request that I copied from Chrome network tab for GraphiQL:
{"query":"query PartnersQuery {\n partners{\n name\n url\n logo\n }\n}","variables":"null","operationName":"PartnersQuery"}
When I copy it to Postman with Content-Type: application/json, I get the following response:
{
"errors": [
{
"message": "Must provide query string."
}
]
}
What can be the cause of this problem? I have not done anything crazy with the schema. Just followed the tutorials from graphene's docs. What else can cause an issue like this?
This error is raised when parse_body is unable to parse the incoming data. I'd start there by looking at the data passed into this method and ensuring it's of the correct type.
For example, the multipart/form-data section naively returns request.POST, which may need to be overwritten to handle, for example, the request that apollo-upload-client sends for file upload handling.
In our case we created a view to both require a login and to support the apollo-upload-client use case and it works fine.
Here's how I was able to get a successful response from Postman using a graphene Django backend with a simple mutation:
Set method to POST
Add the URL to your graphQL endpoint, e.g. http://localhost:8000/api/
Add one header -- key: "Content-Type" , value: "application/json"
Set the body to "raw"
Paste in your query into the body window, e.g. {"query":"{myModels {id}}","variables":"null","operationName":null}
This sounds pretty much like what you did, so you must be close.
I faced the same problem when I try to used graphQl query using POSTMAN,
In POSTMAN send data in row with json type.
You have to make json data grapQl query and mutations data like this
Query Command:
{"query":"{user(id:902){id,username,DOB}}"}
Mutations Command:
{ "query": "mutation {createMutations(reviewer:36, comments:\"hello\",loan: 1659, approved: true ){id}}" }
#commnent: String Type
#data_id:Int Type
#approved:Boolean Type
Checkout sample apps and see how they do things,
e.g.
https://github.com/mjtamlyn/graphene-tutorial
they do the following:
from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
url(r'^explore', GraphQLView.as_view(graphiql=True)),
url(r'^graphql', csrf_exempt(GraphQLView.as_view())),
I encountered exactly the same problem as the original poster, Gasim. Studying the code in 'graphiql.html' I see that they're converting the query string, that goes into the body, into the query parameter in the URL. Thus you end up with this URL being sent via Postman:
http://127.0.0.1:8000/graphql?query=%7B%0A%20%20allCategories%20%7B%0A%20%20%20%20edges%20%7B%0A%20%20%20%20%20%20node%20%7B%0A%20%20%20%20%20%20%20%20name%0A%20%20%20%20%20%20%20%20ingredients%20%7B%0A%20%20%20%20%20%20%20%20%20%20edges%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20node%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20name%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D%0A
It seems nonsensical to me to duplicate precisely what's in the body in the query string in the URL too but that appears to be the only way to get the Graphene server to return a valid response.
Surely this is a bug/shortcoming that will be fixed?
Robert
Enable graphine on django
url(r'^graphql', csrf_exempt(GraphQLView.as_view(graphiql=settings.DEBUG))),
Execute some query and see it is working
On Chrome browser, go to graphiQL endpoint: http://localhost:8000/graphql? open "Developer Tools" in browser and go to "Network" tab.
Execute your query again. Now it appears on list of requests. Now right mouse click on it and copy it "copy as CURL". Now you can strait copy paste it to linux terminal with curl installed. Or like in your case you can try to deduct what is what there, and try to reuse it in your IDE like client like Insomnia or Postman. For instance you may discover that authorisation that works with session on graphiQL enpoint, is not what you want at the end...
curl 'http://localhost:8000/graphql?' -H 'Origin: http://localhost:8000' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.9,pl;q=0.8,de;q=0.7' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Cookie: _ga=GA1.1.1578283610.1528109563; _gid=GA1.1.920024733.1541592686; csrftoken=EGBeegFoyMVl8j1fQbuEBG587nOFP2INwv7Q0Ee6HeHHmsLOPUwRonzun9Y6pOjV; sessionid=4u9vngcnmjh927a9avpssvc4oq9qyqoe' -H 'Connection: keep-alive' -H 'X-CSRFToken: EGBeegFoyMVl8j1fQbuEBG587nOFP2INwv7Q0Ee6HeHHmsLOPUwRonzun9Y6pOjV' --data-binary '{"query":"{\n allStatistics(projectId: 413581, first:25) {\n pageInfo {\n startCursor\n endCursor\n hasPreviousPage\n hasNextPage\n }\n edges {\n cursor\n node {\n id\n clickouts\n commissionCanc\n commissionConf\n commissionLeads\n commissionOpen\n eventDate\n extractTstamp\n hash\n leads\n pageviews\n projectId\n transactionsCanc\n transactionsConf\n transactionsOpen\n }\n }\n }\n}\n","variables":null,"operationName":null}' --compressed
The problem in my code was that I had the URL improperly setup for graphQL. I had the following:
url(r'^graphql/', GraphQLView.as_view())
The forward slash was a huge difference. Removing it fixed the problem. The proper way to do it would be:
url(r'^graphql', GraphQLView.as_view())

how to create an events in facebook using graph api

I am creating facebook application.I want to create a event.I tried following url but does not work for me.
https://graph.facebook.com/profileid/events?access_token=generatedaccess_token&name=somename&location=locationname I am getting json output with blank data.There is nothing in data tag.When I adding method=post,gives me error saying that invalid parameter.
In order to create an event, you have to issue an HTTP POST request. This is straight from the facebook graph api documentation: http://developers.facebook.com/docs/reference/api/page/#events
An HTTP POST request is basically like submitting a form with method="post". You can use cURL to do this fairly easily:
curl \
–F 'access_token=[PAGE_ACCESS_TOKEN]' \
-F 'batch=[ \
{ "method": "POST", \
"relative_url": "[PAGE_ID]/events", \
"body": "name=[EVENT_NAME]&start_time=[UNIX_TIMESTAMP]" \
}, \
]'\
https://graph.facebook.com
You can refer to the section on batch request for more help on this: http://developers.facebook.com/docs/reference/api/batch/