Twilio - creating subaccount and appending to Firebase in Swift - json

I'm creating subaccounts for Twilio using AF.request in Swift, but I'm having issues appending the response to Firebase Realtime Database.
From the result, how can I grab "authToken" so that I can append to the database?
public func createSubAccount(friendlyName: String, SID: String, userAuthToken: String) {
let parameters = ["FriendlyName": friendlyName]
AF.request("https://\(SID):\(userAuthToken)#api.twilio.com/2010-04-01/Accounts.json", method: .post, parameters: parameters).response { response in
print(response.result)
AF.request("https://\(SID):\(userAuthToken)#api.twilio.com/2010-04-01/Accounts.json?FriendlyName=\(friendlyName)&PageSize=5", method: .get, parameters: parameters).responseJSON { response in
print (response.result)
}
}
}
When I run this, I print the following result:
success({
accounts = (
{
"auth_token" = 9d4ffXXXXXXXXXXXXXXXXXX;
"date_created" = "Sat, 08 Oct 2022 22:07:34 +0000";
"date_updated" = "Sat, 08 Oct 2022 22:07:34 +0000";
"friendly_name" = "chris-gmail-com";
"owner_account_sid" = AC916XXXXXXXXXXXXXXXXXX;
sid = ACa9c8XXXXXXXXXXX;
status = active;
"subresource_uris" = {
addresses = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Addresses.json";
applications = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Applications.json";
"authorized_connect_apps" = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/AuthorizedConnectApps.json";
"available_phone_numbers" = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/AvailablePhoneNumbers.json";
balance = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Balance.json";
calls = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Calls.json";
conferences = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Conferences.json";
"connect_apps" = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/ConnectApps.json";
"incoming_phone_numbers" = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/IncomingPhoneNumbers.json";
keys = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Keys.json";
messages = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Messages.json";
notifications = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Notifications.json";
"outgoing_caller_ids" = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/OutgoingCallerIds.json";
queues = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Queues.json";
recordings = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Recordings.json";
"short_codes" = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/SMS/ShortCodes.json";
"signing_keys" = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/SigningKeys.json";
sip = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/SIP.json";
transcriptions = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Transcriptions.json";
usage = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX/Usage.json";
};
type = Trial;
uri = "/2010-04-01/Accounts/ACa9c866aXXXXXXXXXXX.json";
}
);
end = 0;
"first_page_uri" = "/2010-04-01/Accounts.json?FriendlyName=chris-gmail-com&PageSize=5&Page=0";
"next_page_uri" = "<null>";
page = 0;
"page_size" = 5;
"previous_page_uri" = "<null>";
start = 0;
uri = "/2010-04-01/Accounts.json?FriendlyName=chris-gmail-com&PageSize=5&Page=0";
})

Related

Parse Bloomberg API response to JSON in python3

How can I convert the response message that returned from using bloomberg API in (python3 and flask) in to JSON
here is a response example:
ReferenceDataResponse = {
securityData[] = {
securityData = {
security = "FB EQUITY"
eidData[] = {
}
fieldExceptions[] = {
}
sequenceNumber = 0
fieldData = {
PX_LAST = 186.270000
VOLUME = 16746904.000000
}
}
securityData = {
security = "IBM EQUITY"
eidData[] = {
}
fieldExceptions[] = {
}
sequenceNumber = 1
fieldData = {
PX_LAST = 134.400000
VOLUME = 2551009.000000
}
}
}
}
dealing with it with the comming piece of code :
if str(msg.messageType()) == "ReferenceDataResponse":
securities = msg.getElement('securityData')
securities_count = securities.numValues()
for i in range(securities_count):
security = securities.getValueAsElement(i)
ticker = security.getElementAsString('security')
if (security.hasElement('fieldData')):
fields = security.getElement('fieldData')
fields_count = fields.numElements()
for j in range (fields_count):
security_dict = None
field = fields.getElement(j)
f_name = field.name()
f_value = field.getValueAsString()
security_dict = {"ticker":ticker ,"f_name":f_name , "f_value":f_value}
bloom_data.append(security_dict)
give me (Object of type Name is not JSON serializable)
now, I cant not access the name object to reach the name of the fields
any help will be very appreciated
After a lot of search I found this doc that is very helpful for as a schema for using the bloomberg api for dealing with the response ....
Here's the link ==> api schema
example for handeling respnse using python3:
bloom_data = []
if str(msg.messageType()) == "ReferenceDataResponse":
securities = msg.getElement('securityData')
securities_count = securities.numValues()
for i in range(securities_count):
security = securities.getValueAsElement(i)
ticker = security.getElementAsString('security')
if (security.hasElement('fieldData')):
fields = security.getElement('fieldData')
fields_count = fields.numElements()
for j in range (fields_count):
security_dict = None
field = fields.getElement(j)
f_name = field.name()
f_value = field.getValueAsString()
security_dict = {"ticker":ticker ,"f_name":str(f_name) , "f_value":f_value}
bloom_data.append(security_dict)

Vapor MySQL Timestamps Default Values

I am trying to create a model that has various timestamps (createdAt, updatedAt, deletedAt), with default values. How can this be achieved? I tried playing around with the prepare method, but to no avail. Thank you in advance.
This is my current class:
Vapor offers sth like:
static func prepare(on connection: MySQLConnection) -> Future<Void> {
return Database.create(self, on: connection) { builder in
builder.field(for: \.iq, type: .int, .default(.literal("123456")))
...
this should work with Dates as well.
Or you could try to set them in a custom init:
required init(id:Int?, adressLine1:String, adressLine2:String?, city:String, state:String, zip:String) {
self.id = id
self.adressLine1 = adressLine1
self.adressLine2 = adressLine2
self.city:String = city:String
self.state = state
self.zip = zip
self.createdAt = Date() //<---- here
self.updatedAt = Date() //<---- here
self.deletedAt = Date() //<---- here
}
or:
required init(id:Int?, adressLine1:String, adressLine2:String?, city:String, state:String, zip:String,
createdAt:Date = Date()/*<--- here*/, updatedAt:Date = Date()/*<--- here*/,deletedAt:Date = Date()/*<--- here*/) {
self.id = id
self.adressLine1 = adressLine1
self.adressLine2 = adressLine2
self.city:String = city:String
self.state = state
self.zip = zip
self.createdAt = createdAt
self.updatedAt = updatedAt
self.deletedAt = deletedAt
}

Reading parameters from json using swift 2

iv'e been trying for few days to get parameters from specific json structure with no success so far. I have a NSDictionary that get json data (i need the mToken and data from mHeader for example)
{
"$id" = 1;
mHeaders = (
{
"$id" = 4;
mPoints = 0;
mRealLeagueId = 57172a6e2276fe28bcf0d91c;
mTeamId = 57172a762276fe28bcf0e053;
mTeamLogo = avatar;
mTeamName = "Hungry Animals";
}
);
mToken = "5k8ziTBn0G5Gozs7qz68LCLBfLSgymOcLwRshMax1Q5pZi4bx6hbEOFgupoXrBNNGzsWosLs6KPsK6cG1kk/9o5778Y7JEKfo3CAPXS7qAg=";
mUser = {
"$id" = 2;
mAge = 42;
mCreateDate = "2016-04-20T07:06:30.507Z";
mEmail = "email0#gmail.com";
mFirstName = Alesandro;
mGender = 1;
mId = 57172a762276fe28bcf0e06d;
mLastLogin = "2016-04-21T07:20:40.402Z";
mLastName = Zohar;
mLogo = avatar;
mNick = "Big Boss 0";
mRegion = Global;
mTeams = (
{
"$id" = 3;
mRealLeagueId = 57172a6e2276fe28bcf0d91c;
mTeamId = 57172a762276fe28bcf0e053;
}
);
mTokens = 9644998;
};
}
So you have a dictionary after parsing the json. You need mToken which in root level of the json data, you can simply get the value by
jsonDict["mToken"]
Your mHeader is an array of dictionary so for getting the value, Do like this
for dict in jsonDict["mHeaders"] as! Array<NSDictionary> {
print(dict["mRealLeagueId"]) //prints 57172a6e2276fe28bcf0d91c
print(dict["mTeamId"]) //57172a762276fe28bcf0e053
}
Hope this helps

Facebook Graph API - JSON data

I am getting the following data in JSON format by the Facebook graph API. However it looks like it is in invalid JSON format. The JSON formatter says that the error is in line 1. What is this error ?
{
data = (
{
application = {
id = 2409997254;
name = Likes;
};
"created_time" = "2013-05-05T07:51:41+0000";
from = {
id = 100000347121257;
name = "Rishab Gulati";
};
id = "notif_746853089_182660043";
link = "http://www.facebook.com/photo.php?fbid=10151457234013090&set=a.427064503089.223857.746853089&type=1";
object = "<null>";
title = "Rishab Gulati, Deepika Gurnani and 2 other people like your photo.";
to = {
id = 746853089;
name = "Ashish Agarwal";
};
unread = 1;
"updated_time" = "2013-05-05T10:48:33+0000";
}
);
paging = {
next = "https://graph.facebook.com/746853089/notifications?format=json&access_token=**xxxxxxxxxx";
previous = "https://graph.facebook.com/746853089/notifications?format=json&access_token=**SNIP**&limit=5000&since=1367740301&__paging_token=notif_746853089_182660043&__previous=1";
};
summary = {
"unseen_count" = 1;
"updated_time" = "2013-05-05T10:48:33+0000";
};
}
This data is incorrect and isn't what Facebook supplies
{
"data": [
{
Where as your JSON above shows
{
data = (
{
There is a ( when there should be a {
Also consider not giving your access token out in public.

How to fix the lambda expression delegate error?

I am using this method to get data
private void getNews(int cat_id, int page)
{
this.progress.Visibility = Visibility.Visible;
var m = new SharpGIS.GZipWebClient();
Microsoft.Phone.Reactive.Observable.FromEvent<DownloadStringCompletedEventArgs>(m, "DownloadStringCompleted").Subscribe(l =>
{
try
{
//List<NewsKeys> deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(r.EventArgs.Result);
ObservableCollection<NewsKeys> deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(l.EventArgs.Result);
foreach (NewsKeys item in deserialized)
{
items.Add(new NewsKeys { nId = item.nId, title = item.title, shortDesc = item.shortDesc, fullDesc = item.fullDesc, tags = item.tags, smallPic = item.smallPic, bigPic = item.bigPic, video = item.video, audio = item.audio, youtube = item.youtube, doc = item.doc, date_create = item.date_create, date_modify = item.date_modify, date_publish = item.date_publish, catId = item.catId, viewOrder = item.viewOrder, viewCount = item.viewCount, viewStatus = item.viewStatus, viewHome = item.viewHome, uId = item.uId, uFname = item.uFname });
}
}
catch (Exception)
{
MessageBox.Show("Sorry, Some unexpected error.");
}
});
m.DownloadStringAsync(new Uri(Resource.NEWS_API+cat_id+"&page="+page));
}
The error i get is
Error 1 Cannot convert lambda expression to type 'System.IObserver>' because it is not a delegate type C:\Users\Adodis\Documents\Visual Studio 2010\Projects\TV\NewsListPage.xaml.cs 51 133
I have tried all the fixes but unable to fix this problem. Am using the same block in different method in a different class it is working fine but, this method in this class killing me. Please help me if you have idea on this.
Thanks in advance.
Try this (I've separated the Select and Subscribe operations):
var m = new SharpGIS.GZipWebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(m, "DownloadStringCompleted")
.Select(l => l.EventArgs.Result)
.Subscribe(res =>
{
try
{
var deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(res);
foreach (NewsKeys item in deserialized)
{
items.Add(
new NewsKeys
{
nId = item.nId,
title = item.title,
shortDesc = item.shortDesc,
fullDesc = item.fullDesc,
tags = item.tags,
smallPic = item.smallPic,
bigPic = item.bigPic,
video = item.video,
audio = item.audio,
youtube = item.youtube,
doc = item.doc,
date_create = item.date_create,
date_modify = item.date_modify,
date_publish = item.date_publish,
catId = item.catId,
viewOrder = item.viewOrder,
viewCount = item.viewCount,
viewStatus = item.viewStatus,
viewHome = item.viewHome,
uId = item.uId,
uFname = item.uFname
});
}
}
catch (Exception)
{
MessageBox.Show("Sorry, Some unexpected error.");
}
});
m.DownloadStringAsync(new Uri("Resource.NEWS_API" + cat_id + "&page=" + page));