How to make a POST request to Twilio to call a number with urequests - url

I have recently starting doing things with a raspberry pi zero W and wanted to be able to call a number from it.
Unfortunately it seems very hard to use the normal Twilio library because the pi uses MicroPython so I have to use the raw API.
I also gathered that the API uses the content type x-www-form-urlencoded which urequests seems to have a hard time interacting with.
This is my code so far
url = f"https://api.twilio.com/2010-04-01/Accounts/{TWILIO_USER}/Calls.json"
def call() -> None:
body = {"To": CALLING_NUMBER, "From": CALLER_NUMBER}
response = urequests.post(url, json=body, auth=(TWILIO_USER, TWILIO_KEY))
print("Status Code", response.status_code)
print("JSON Response ", response.json())
however I get the error
{'code': 21201, 'more_info': 'https://www.twilio.com/docs/errors/21201', 'message': "No 'To' number is specified", 'status': 400}
I have tried a ton of stuff like url encoding the body myself, using it as the parameter for data, json.dumpsing it, nothing seemed to work. Any help would be greatly appreciated.
Please remember I am limited by the picos standard libraries.

It seems I was close. All I had to do was copy paste urllib's urlencode and use it on body, then it ended up working.

Related

Krakend: Use previous backend response data to populate post body using lua

I am new to Kraken but quite excited about it. What I am trying to do currently is to have two sequential backends where I would like to use parts of the response from the first backend to populate the body of the second request using Lua. the only issue I am having is to get a hold of the data that I can get via {resp0} if I use it outside the Lua scripts.
This is the part of the krakend.json where I would like to access the previous response:
"extra_config": {
"modifier/lua-backend": {
"sources": [ "/etc/krakend/config/lua/enrichRequestBody.lua" ],
"pre": " populate_request_body(request.load(), {resp0});",
"live": false
}
Any input or suggestions would be much appreciated!
Thanks
I have been trying finding {resp0} or the corresponding value from debugging but no luck. I haven't found any documentation or examples for this in the Kraken documentation

Gmail API, Reply to thread not working / forwarding

I'm using the google gmail api in swift. All is working well, it's compiling etc.
I'm now trying forward an email, the only way I see this possible so far is by using a thread id.
So I'm using the API tester found here to send tests. Will will focus on this. It can be found here1
So I've input this, the "raw" is Base64 URL encoded string.
{
"raw": "VG86ICBlbWFpbFRvU2VuZFRvQGdtYWlsLmNvbSAKU3ViamVjdDogIFRoZSBzdWJqZWN0IHRlc3QKSW4tUmVwbHktVG86ICBteUVtYWlsQGdtYWlsLmNvbQpUaHJlYWRJZDogIDE1YjkwYWU2MzczNDQ0MTIKClNvbWUgQ29vbCB0aGluZyBpIHdhbnQgdG8gcmVwbHkgdG8geW91ciBjb252by4u",
"threadId": "15b90ae637344412"
}
The "raw" in plain text is
To: emailToSendTo#gmail.com
Subject: The subject test
In-Reply-To: myEmail#gmail.com
ThreadId: 15b90ae637344412
Some Cool thing i want to reply to your convo..
when I execute it I get this back
{
"id": "15b944f6540396df",
"threadId": "15b90ae637344412",
"labelIds": [
"SENT"
]
}
But when I check both email account, from and to. None of them say the previous messages but are in the same "thread" or convo.
If anyone can help it would be much appreciated I've spent all day on this issue and half of yesterday and did TONS of research on it.
as stated here I should I'm adding the threaded and In-Reply-To in the right way I believe
The ID of the thread the message belongs to. To add a message or draft to a thread, the following criteria must be met:
The requested threadId must be specified on the Message or Draft.Message you supply with your request.
The References and In-Reply-To headers must be set in compliance with the RFC 2822 standard.
The Subject headers must match.

React Native - Interact with API - Special Characters Causing Issues - What's the best way to do this?

I cannot consistently successfully send form variables that may/may not include special characters e.g. ? & #
Depending on where I try to escape the chars I encounter different errors when reading the data server-side.
I am aware that an update is due for React Native 0.7 to include formdata but wondered if I could safely post objects without needing this.
Someone has already posted a similar issue but no example code was posted to illustrate the POST working:
How to post a form using fetch in react native?
I have tried - amongst other things :
fetch(APIURL, {
method: 'POST',
body: JSON.stringify({
object1: {
param1a: "value 1a",
param1b: "value 1b - with bad chars & # ?",
},
object2:
{
param2a: "value 2a",
param2b: 0,
}
})
})
but it groups the data into a single unnamed parameter (changing the API to accept this is not an option).
also this:
fetch(APIURL, {
method: 'GET',
accessPackage: JSON.stringify({
accessToken: "abc123",
tokenType: 2,
}),
taggData: JSON.stringify({
title: "test",
wishlistID: 0,
anotherVar: "anotherVal"
})
})
I wish to receive the data as two strings that can be parsed as json objects at the other end.
Looking at the the fetch repo https://github.com/github/fetch hasn't helped as this assumes the post with be a full JSON post (which it isn't) or uses FormData which isn't available to React Native yet.
Another solution may be to safely encode/serialise all of the data to URL parameters but this has also proven inconsistent so far especially with the # char.
What's the best way to do this?
"it groups the data into a single unnamed parameter (changing the API
to accept this is not an option)."
It would, because you've set the post body. This is how it's supposed to work.
I wish to receive the data as two strings that can be parsed as json objects at the other end.
You can do whatever you want, but there's no magic happening here. You will receive a single string, the string you set body to. Likewise, the post body can contain anything but shouldn't get confused with "special" characters. Most likely it is your server-side that is causing the problems.
If you want to use FormData then I think it'll be in v0.7.0 which should be out any day now, or you could probably just include the JS file in your own project. You can find it here. Usage examples are in the UIExplorer demo.

How to create a bigquery table and import from cloud storage using the ruby api

Im trying to create a table on BigQuery - I have a single dataset and need to use the api to add a table and import data (json.tar.gz) from cloud storage. I need to be able to use the ruby client to automate the whole process. I have two questions:
I have read the docs and tried to get it to upload (code below) and have not been successful and have absolutely no idea what Im doing wrong. Could somebody please enlighten me or point me in the right direction?
Once I make the request, how do I know when the job has actually finished? From the API, I presume Im meant to use a jobs.get request? Having not completed the first part I have been unable to get to look at this aspect.
This is my code below.
config= {
'configuration'=> {
'load'=> {
'sourceUris'=> ["gs://person-bucket/person_json.tar.gz"],
'schema'=> {
'fields'=> [
{ 'name'=>'person_id', 'type'=>'integer' },
{ 'name'=> 'person_name', 'type'=>'string' },
{ 'name'=> 'logged_in_at', 'type'=>'timestamp' },
]
},
'destinationTable'=> {
'projectId'=> "XXXXXXXXX",
'datasetId'=> "personDataset",
'tableId'=> "person"
},
'createDisposition' => 'CREATE_IF_NEEDED',
'maxBadRecords'=> 10,
}
},
'jobReference'=>{'projectId'=>XXXXXXXXX}
}
multipart_boundary="xxx"
body = "--#{multipart_boundary}\n"
body += "Content-Type: application/json; charset=UTF-8\n\n"
body += "#{config.to_json}\n"
body += "--#{multipart_boundary}\n"
body +="Content-Type: application/octet-stream\n\n"
body += "--#{multipart_boundary}--\n"
param_hash = {:api_method=> bigquery.jobs.insert }
param_hash[:parameters] = {'projectId' => 'XXXXXXXX'}
param_hash[:body] = body
param_hash[:headers] = {'Content-Type' => "multipart/related; boundary=#{multipart_boundary}"}
result = #client.execute(param_hash)
puts JSON.parse(result.response.header)
I get the following error:
{"error"=>{"errors"=>[{"domain"=>"global", "reason"=>"wrongUrlForUpload", "message"=>"Uploads must be sent to the upload URL. Re-send this request to https://www.googleapis.com/upload/bigquery/v2/projects/XXXXXXXX/jobs"}], "code"=>400, "message"=>"Uploads must be sent to the upload URL. Re-send this request to https://www.googleapis.com/upload/bigquery/v2/projects/XXXXXXXX/jobs"}}
From the request header, it appears to be going to the same URI the error says it should go to, and I am quite at a loss for how to proceed. Any help would be much appreciated.
Thank you and have a great day!
Since this is a "media upload" request, there is a slightly different protocol for making the request. The ruby doc here http://rubydoc.info/github/google/google-api-ruby-client/file/README.md#Media_Upload describes it in more detail. I'd use resumable upload rather than multipart because it is simpler.
Yes, as you suspected, the way to know when it is done is to do a jobs.get() to look up the status of the running job. The job id will be returned in the response from jobs.insert(). If you want more control, you can pass your own job id, so that in the event that the jobs.insert() call returns an error you can find out whether the job actually started.
Thank you for that. Answer resolved. Please see here :
How to import a json from a file on cloud storage to Bigquery
I think that the line of code in the docs for the resumable uploads section (http://rubydoc.info/github/google/google-api-ruby-client/file/README.md#Media_Upload) should read:
result = client.execute(:api_method => drive.files.insert,
Otherwise, this line will throw an error with 'result' undefined:
upload = result.resumable_upload

How to Parse Ksoap2 Response in Android

I already searched and read a lot of tutorial how to parse Ksoap2 response using C# ASP.net Web Service. It's very confusing what should I pick because the others say that "it's wrong this is the right way" and the others say "no that was also wrong" Now I really don't know what I'm going to use to parse my web service response.
this is my response.
anyType{NewDataSet=anyType{Table=anyType{id=1; autoID=aa; name=bb; company=bb; address=bb; position=bb; email=bb; conTactMobile=bb; contactTelephone=bb; companyLogo=bb; photo=bb; }; }; }
Can anybody suggest what is the best way to parse this kind of response.
any thoughts will be Highly appreciated.
Well Here are Some steps you can follow to parse your response:
SoapObject response = (SoapObject) envelope.getResponse();
After that extract first property i.e:
SoapObject NewDataSet = (SoapObject) response.getProperty(0);
SoapObject table = NewDataSet.getProperty(0);
get each property in table as,for ex:-
String iD=table.getProperty(0);
String autoID=table.getProperty(1);
This is one of the solution(I cant say if it is the best one or not),see is it solves your problem..

Resources