I am following the Twilio tutorial to setup an iOS project. Since it requires a backend, I have opted for Python (I am an iOS developer with 'zero' knowledge about Python) So the question might probably be a dumb one, but I do not get the proper syntax to look for.
Objective:
To fetch all the call logs and conference logs & return them as JSON response.
My Code:
#app.route('/getRecordings', methods=['GET'])
def getRecordings():
client = Client(ACCOUNT_SID, ACCOUNT_AUTH_TOKEN)
recordings = []
for record in client.calls.list():
recordings.append(record.sid)
conferences = []
for conf in client.conferences.list():
conferences.append(conf.sid)
return jsonify(calls=recordings, conferences=conferences)
Response:
I am getting the proper response, since I have appended only the SID property of each call.
{
"calls": [
"CAxxx",
"CAxxx",
],
"conferences": [
"CFxxx",
"CFxxx",
]
}
But I would like to get the complete details of each record as shown in the output tab of this sample from Twilio (Reference: https://www.twilio.com/docs/api/voice/conference)
When I try to JSONify the record, it says it cannot JSONify the object of this type.
I understand that I should convert the object to a model and append it, but how can I do that? Any links or leads to help getting this sorted are much appreciated.
You need to create a list of dictionaries with the required values. Something like this:
for record in client.calls.list():
call = {"account_sid": record.account_sid, "api_version": record.api_version, "date_created": record.date_created, "etc": record.etc}
recordings.append(call)
That should give you a response as follows:
{
"calls": [
{
"accound_sid": "1234",
"api_version": "2010-04-01",
"date_created": "Wed, 18 Aug 2010 20:20:06 +0000",
"etc": "etc",
},
{
"accound_sid": "4321",
"api_version": "2010-04-01",
"date_created": "Wed, 18 Aug 2010 20:20:06 +0000",
"etc": "etc",
}
]
}
Twilio developer evangelist here.
If you want the full JSON response proxied to your application, then you may find it easier to avoid the Twilio library and just make requests to the JSON API endpoints and send the response straight on.
For example, to get the list of calls with Python's Requests library you would do something like this:
#app.route('/getCalls', methods=['GET'])
def getCalls():
url = 'https://api.twilio.com/2010-04-01/Accounts/YOUR_ACCOUNT_SID/Calls/.json'
request = requests.get(url, auth=(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN)
resp = Response(response=request.text,
status=200,
mimetype="application/json")
return resp
Let me know if that helps at all.
Related
Edit: Since this question is getting a good amount of views, I'd like to let you all know before you waste hours of your life on the upload endpoint that it currently requires you to manually click confirm in the app. So it doesn't allow you to fully automate uploads. To anyone which this saves time, you're welcome :)
Currently trying to implement the TikTok api into one of my projects. However having a few difficulties with a specific endpoint. Not sure if its an error on my part or on Tiktoks.
Upon making the below request I am recieving an invalid request body error message. I have followed their documentation to the T so unsure why this is happening?
https://developers.tiktok.com/doc/login-kit-user-info-basic
data = {
"access_token": access_token,
"open_id": open_id,
"fields": [
"open_id",
"union_id",
"avatar_url",
"avatar_url_100",
"avatar_url_200",
"avatar_large_url",
"display_name"
]
}
user_info = requests.post("https://open-api.tiktok.com/user/info/", data=data)
print(user_info.json())
{'data': {}, 'error': {'code': 6007055, 'log_id': '', 'message': 'invalid request body'}}
Use json parameter instead of data
import requests
data = {
"access_token": access_token,
"open_id": open_id,
"fields": [
"open_id",
"union_id",
"avatar_url",
"avatar_url_100",
"avatar_url_200",
"avatar_large_url",
"display_name"
]
}
user_info = requests.post("https://open-api.tiktok.com/user/info/", json=data)
print(user_info.json())
So first of all thanks, I'm really new to python and I am trying to understand APIs, I'm currently trying to log in into /inventory/json/v/1.4.1/<request_code>?jsonRequest=<json_request_content> which is the Earth Explorer API, and the first step is to Login, and according to the documentation I am supposed to use POST instead of GET, so here is what I got so far, and it works but this is what I
import requests
import requests
user = 'xxxxx'
psword = 'xxxxx'
input_data= {'username':user,'password':psword,'catalogId':'EE'}
test=requests.post('https://earthexplorer.usgs.gov/inventory/json/v/1.4.0/login?jsonRequest=input_data)')
print(test.text)
print(test.status_code)
{
"errorCode": "AUTH_ERROR",
"error": "Passing credentials via URL is not permitted - use a POST request",
"data": null,
"api_version": "",
"access_level": "guest",
"executionTime": 0
}
200
I have no idea what to do, thank you so much. This is the documentation for the earth explorer API, thank you so much https://earthexplorer.usgs.gov/inventory/documentation/json-api?version=1.4.1#login
I have encountered the same problem while working with Earth Explorer API and managed to solve it by reading usgs package code. Basically, the problem is that you must send the request body as a string. That is, your request body must look like this when printed
{
"jsonRequest": "{\"username\": \"???\", \"password\": \"???\", \"catalogId\": \"???\"}"
}
You can achieve this using
import json
import requests
req_params = {
'username': '???',
'password': '???',
'catalogId': '???',
}
req_txt = json.dumps(req_params)
req_body = {
'jsonRequest': req_txt,
}
resp = requests.post('<LOGIN URL HERE>', req_body)
This code is actually taken from usgs package I mentioned, so you should refer to it if you have any additional questions.
I'm trying to make a data partition refresh (post) following this azure documentation : https://learn.microsoft.com/en-us/azure/analysis-services/analysis-services-async-refresh
Either with post or get I got 401 Unauthorized (Even when the service is Off !).
I got the token from azure AD (ServicePrincipalCredential).
I added the AD as Analysis Services Admins (https://learn.microsoft.com/en-us/azure/analysis-services/analysis-services-server-admins)
I gave the owner role to AD in Analysis Services IAM.
it worked with Analysis Services management rest api (https://learn.microsoft.com/en-us/rest/api/analysisservices/operations/list) With the same authentification (got code response 200)
My python code :
from azure.common.credentials import ServicePrincipalCredentials
import requests
credentials = ServicePrincipalCredentials(client_id="ad_client_id",
secret="ad_secret",
tenant="ad_tenant")
token = credentials.token
url = "https://westeurope.asazure.windows.net/servers/{my_server}/models/{my_model}/refreshes"
test_refresh = {
"Type": "Full",
"CommitMode": "transactional",
"MaxParallelism": 1,
"RetryCount": 1,
"Objects": [
{
"table": "my_table",
"partition": "my_partition"
}
]
}
header={'Content-Type':'application/json', 'Authorization': "Bearer {}".format(token['access_token'])}
r = requests.post(url=url, headers=header, data=test_refresh)
import json
print(json.dumps(r.json(), indent=" "))
Response I got :
{
"code": "Unauthorized",
"subCode": 0,
"message": "Authentication failed.",
"timeStamp": "2019-05-22T13:39:03.0322998Z",
"httpStatusCode": 401,
"details": [
{
"code": "RootActivityId",
"message": "aab22348-9ba7-42c9-a317-fbc231832f75"
}
]
}
I'm hopeless, could you please give me somes help to make this clear ?
Finally I resolved the issue.
I had wrong token. The api expect an OAuth2.0 authentification token (The Azure analysis services rest api documentation ins't very clear about the way to get one)
For thoses will encounter the same issu there is the way to get one.
from adal import AuthenticationContext
authority = "https://login.windows.net/{AD_tenant_ID}"
auth_context = AuthenticationContext(authority)
oauth_token = auth_context.acquire_token_with_client_credentials(resource="https://westeurope.asazure.windows.net", client_id=AD_client_id, client_secret=AD_client_id)
token = oauth_token['accessToken']
Documentation about this :
https://learn.microsoft.com/en-us/python/api/adal/adal.authentication_context.authenticationcontext?view=azure-python#acquire-token-with-client-credentials-resource--client-id--client-secret-
https://github.com/AzureAD/azure-activedirectory-library-for-python/wiki/ADAL-basics
Most likely your token is not right.
Have you tried validating your token? Use something like http://calebb.net/
I see some examples of ServicePrincipalCredentials that stipulate the context or resource like this:
credentials = ServicePrincipalCredentials(
tenant=options['tenant_id'],
client_id=options['script_service_principal_client_id'],
secret=options['script_service_principal_secret'],
resource='https://graph.windows.net'
Good samples here:
https://www.programcreek.com/python/example/103446/azure.common.credentials.ServicePrincipalCredentials
I think the solution is try a couple more things that make sense and follow the error details.
You need token which has resource (audience) set to https://*.asazure.windows.net
For token validation I like https://jwt.io
Also if you want to automate this properly you have two options
Either by Logic Apps
or with Azure Data Factory
Both of which I have very detailed posts on if you want to check them out
https://marczak.io/posts/2019/06/logic-apps-refresh-analysis-services/
https://marczak.io/posts/2019/06/logic-app-vs-data-factory-for-aas-refresh/
I am trying to create Asana task using oAuth, so far it was working fine, but suddenly its not working anymore.
It is throwing back the following response:
{"errors":[{"message":"missing both `parent` and `workspace` fields; at least one required"}]}
Here is what I am doing
import requests
import json
data = {
'workspace':'<my workspace id>',
'assignee':'me',
'name':'My awesome task',
'notes':'My task notes'
}
headers ={'Authorization':'Bearer <my token>','Content-Type':'application/json'}
response = requests.post('https://app.asana.com/api/1.0/tasks',
headers=headers,
data=json.dumps(data))
print response.text
It looks like you're missing a data parameter in the payload. It's a common gotcha, but when you post JSON data to the API you need to send something that looks like this:
{
"data": {
"name": "This is my task",
"workspace": 1234,
...
}
}
In this case, you should be able to fix it by simply changing the last parameter to data=json.dumps({ 'data': data }).
Hope that helps!
When I look at the documentation for passing parameters to the Jasper Report REST 2 API here: http://community.jaspersoft.com/documentation/jasperreports-server-web-services-guide/v550/running-report-asynchronously I see that I need to have a "parameters" dict. The example in the link shows the XML which is not all that useful since it's unclear exactly what the equivalent JSON should look like. The closest I could find is in this link: http://community.jaspersoft.com/documentation/jasperreports-server-web-services-guide/v56/modifying-report-parameters. Now, I am sending the equivalent of that to the server (and every other permutation I can think of), and I continue to get a "400 Client Error: Bad Request" back. I could really use an exact example of the python code to generate the required "parameters" parameter for say "my_parameter_1="test_value_1".
Here is my current POST data (with a few params missing for brevity). I know this is correct since the report works fine if I omit the "parameters" parameter:
{
'outputFormat': 'pdf',
'parameters': [{'name': 'ReportID', 'value': ['my_value_1']}],
'async': 'true',
'pages': '',
'interactive': 'false'
}
Nice Job there Staggart. I got it now. Because I wasn't reading with max. scrutinity, I wasted some additional time. So the interested coder is not only advised to be aware of the nested, syntactictally interesting reportParameter-property, but especially that the value-property inside that is an array. I suppose one could pass some form of Lists/Arrays/Collections here?
What irritated me was, if I should construct more than one "reportParameter" property, but that would be nonsense according to
Does JSON syntax allow duplicate keys in an object.
So just for the record, how to post multiple parameters:
{
"reportUnitUri": "/reports/Top10/Top10Customers",
"async": true,
"freshData": true,
"saveDataSnapshot": false,
"outputFormat": "pdf",
"interactive": false,
"ignorePagination": true,
"parameters": {
"reportParameter": [
{
"name": "DATE_START_STRING",
"value": ["14.07.2014"]
},
{
"name": "DATE_END_STRING",
"value": ["14.10.2014"]
}
]
}
}
If someone accidently is struggling with communicating with jasper via REST and PHP. Do yourself a favour and use the Requests for PHP instead of pure CURL. It even has a fallback for internally using Sockets instead of CURL, when latter isn't available.
Upvote for you Staggart.
OK, thanks to rafkacz1 # http://community.jaspersoft.com/questions/825719/json-equivalent-xml-post-reportexecutions-rest-service who posted an answer, I figured it out. As he report there, the required format is:
"parameters":{
"reportParameter":[
{"name":"my_parameter_1","value":["my_value_1"]}
]
}
Pay particular attention to the plurality of "reportParameter".
Here is an example that worked for me. Im using Python 2.7, and the community edition of Jaspersoft. Like the C# example above, this example also uses the rest v2 which made it very simple for me to download a pdf report quickly
import requests
sess = requests.Session()
auth = ('username', 'password')
res = sess.get(url='http://your.jasper.domain:8080/jasperserver/', auth=auth)
res.raise_for_status()
url = 'http://your.jasper.domain:8080/jasperserver/rest_v2/reports/report_folder/sub_folder/report_name.pdf'
params = {'Month':'2', 'Year':'2017','Project': 'ProjectName'}
res = sess.get(url=url, params=params, stream=True)
res.raise_for_status()
path = '/path/to/Downloads/report_name.pdf'
with open(path, "wb") as f:
f.write(res.content)
Here's a full example about generate a report using Rest V2, in my case it's running on C#:
try {
var server = "http://localhost:8080/jasperserver";
var login = server + "/rest/login";
var report = "/rest_v2/reports/organization/Reports/report_name.pdf";
var client = new WebClient();
//Set the content type of the request
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
//Set the username and password
NameValueCollection parametros = new NameValueCollection();
parametros.Add("j_username", "jasperadmin");
parametros.Add("j_password", "123456");
//Request to login
client.UploadValues(login, "POST", parametros);
//Get session cookie
string session = client.ResponseHeaders.Get("Set-Cookie");
//Set session cookie to the next request
client.Headers.Add("Cookie", session);
//Generate report with parameters: "start" and "end"
var reporte = client.DownloadData(server + report + "?start=2015-10-01&end=2015-10-10");
//Returns the report as response
return File(reporte, "application/pdf", "test.pdf");
}catch(WebException e){
//return Content("There was a problem, status code: " + ((HttpWebResponse)e.Response).StatusCode);
return null;
}