How to deserialize the GraphQL server response to object? - asp.net-core

How to convert the GraphQL response to object on the client?
I do this way:
var request = new GraphQLRequest
{
Query = #"{customer(id:4){id,firstName,lastName,contact,email}}"
};
var jsonSerializer = new njs.NewtonsoftJsonSerializer();
using var graphQLClient = new GraphQLHttpClient("https://localhost:5011/graphql/", jsonSerializer);
//var response = await graphQLClient.SendQueryAsync<Customer>(request);
var response = await graphQLClient.SendQueryAsync<dynamic>(request);
var graphQLQueryType = #"customer";
var cust = response;//.Data..customer;
var stringResult = response.Data.ToString();
var resultzzz = JsonConvert.DeserializeObject<List<Customer>>(stringResult);
and the result as a string is:
stringResult = "{\r\n "customer": {\r\n "id": "4",\r\n "firstName": "Name#4",\r\n "lastName": "LastName#4",\r\n "contact": "Contact#4",\r\n "email": "you#4#mai.com"\r\n }\r\n}"
It is ok.
But I need to deserialize this response to object class Customer.
and this
var resultzzz = JsonConvert.DeserializeObject(stringResult);
gives me:
ex = {"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[GraphQL.Client.Example.Customer]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error eith...
`
What I do wrong? How to fix it?

Related

Update .gitlab-ci.yml file in GitLab using Gitlab API in C#

I am working on a project that has a file .gitlab-ci.yml in master branch. I am trying to update that .yml file using gitlab api (https://docs.gitlab.com/ee/api/commits.html#create-a-commit-with-multiple-files-and-actions) but using it from a asp.net core 5 application.
Here is my try. But I am getting 400 bad request error. Kindly help to find out what is wrong I am doing here.
public IActionResult Update()
{
var url = $"{ProjectUrl}/{ProjectId}/repository/commits/";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "PUT";
httpRequest.Headers["PRIVATE-TOKEN"] = ClientSecret;
httpRequest.ContentType = "application/json";
var str =
#"{'branch': 'master',
'commit_message': 'some commit message',
'actions': [
{
'action': 'update',
'file_path': '.gitlab-ci.yml',
'content': 'some content'
}
}";
var data = str;
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); // I'm getting 400 Bad request error here
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
// rest of the code goes here
}
return View();
}
Well after rewriting the code, finally I am able to make it works. Posting my solution here in a hope that someone will be benefited from this. Cheers!
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("PUT"), "https://ProjectUrl/api/v4/projects/projectid/repository/%2Egitlab%2Dci.yml"))
{
request.Headers.TryAddWithoutValidation("PRIVATE-TOKEN", "<your_private_token>");
request.Content = new StringContent("{\"branch\": \"master\", \"author_email\": \"user#email.com\", \"author_name\": \"user\", \n \"content\": \"some content\", \"commit_message\": \"update file\"}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
}
}

How do I get specific value from JSON string in Google Script?

I'm trying to extract a specific value from this json file:
An example value I'm looking for is exDividendDate, fmt : 2020-09-24.
The code I've written to extract the value doesn't doesn't extract this or any other value and I'm not sure why. Any help would be greatly appreciated.
The error I get in the Google Apps Script is:
TypeError: Cannot read property 'earningsDate' of undefined (line 44,
file "Stock Database"
function callAPI(symbol) {
// Call the API
var url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/'
var modules = "?modules=calendarEvents"
var response = UrlFetchApp.fetch(url + symbol + modules);
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
console.log(data)
return JSON.parse(json)
}
function displayFinancials() {
// Load sheets
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results");
var modelSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Financial Ratios Model");
// Get model input data
var company = "Apple"
var symbol = "AAPL"
// call the API
var api = callAPI(symbol);
var results = api[0];
// Output the API result
var output = [company, symbol, results.exDividendDate.fmt]
console.log(output);
dataSheet.appendRow(output)
}
When I saw the JSON data, it seems that exDividendDate is callAPI(symbol).quoteSummary.result[0].calendarEvents. So how about the following modification?
From:
var results = api[0];
To:
var results = api.quoteSummary.result[0].calendarEvents;

read data from Map<String, Object>

I get these type of data from some api. I want to read data from "FK_User" which seems an object, when
I read data like this i get this error:
The method '[]' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
print(a["FK_User"]["username"]);
and the data is like this:
var a = {
"ID": "dummyID",
"FK_User": {
"username": "dummyID",
},
"Somefield": "dymmy",
}
var b = a["FK_User"]["username"];
how can I read this type of data?
Map<String, dynamic> a = {
"ID": "dummyID",
"FK_User": {
"username": "dummyID",
},
"Somefield": "dymmy",
};
var b = a["FK_User"]["username"]; // dummyID
Map<String,dynamic> a_map = Map.castFrom(a);
Map<String,dynamic> fk_user_map = Map.castFrom(a_map["FK_user"]);

How to get Multiple Key Value in Dart Http

Please How Can I get this kind of API response in Flutter using http with FutureBuilder.
"GLODATA": {
"1000": {
"pname": "GLO 1.0GB/14days",
"price": "470",
"pld": "1000"
},
"1600.01": {
"pname": "GLO 2.0GB/30days",
"price": "940",
"pld": "1600.01"
},
"3750.01": {
"pname": "GLO 4.5GB/30days",
"price": "1900",
"pld": "3750.01"
},
"5000.01": {
"pname": "GLO 7.2GB/30days",
"price": "2430",
"pld": "5000.01"
}
},
I think in your case, you will need to do something like this:
Api:
Future<http.Response> getData() async {
final _api = "http://yourendpointhere";
http.Response response = await http.get(_api);
if (response.statusCode != 200) {
throw Exception("Request failed...");
}
return response;
}
Then consume your api:
http.Response response = await _apiInstance.getData();
if (response.body != null && response.body.isNotEmpty) {
String source = Utf8Decoder().convert(response.bodyBytes);
Map<String, Map<String, dynamic>> data = Map();
data = Map<String, Map<String, dynamic>>.from(json.decode(source));
}
After that, you can create a factory constructor in your model class, receiving that map and turning it into an instance of your class.

How can I get data from Bitfinex authenticated api endpoints using Google sheets?

Using Google sheets, I have stored my api_key and api_secret in the Property service section of user info as respectively "api_key" and api_secret".
I want to get wallet info from my account. The code I have written is as follows:
function wallet() {
var api_key = PropertiesService.getScriptProperties().getProperty('api_key');
var api_secret = PropertiesService.getScriptProperties().getProperty('api_secret');
var response = UrlFetchApp.fetch("https://api.bitfinex.com/v2/auth/r/wallets", api_key, api_secret);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet");
var result = JSON.parse(response.getContentText());
var wallet_btc = result.BALANCE
}
When I run in debug mode the error message is:
Cannot find method fetch(string,null,null). (line 13, file "Code")
Is this approach wrong, the code wrong, or both?
Many thanks.
How about the following modifications?
Modification points :
The parameters for UrlFetchApp.fetch() are UrlFetchApp.fetch(url, params). And params is an object.
This is the reason of error Cannot find method fetch(string,null,null). (line 13, file "Code").
When I saw the sample scripts for Bitfinex API, the request body has to be created using api_key, api_secret, nonce, body and signature. And signature is encrypted by HMAC_SHA_384 and converted to the string of the unsigned hexadecimal.
The sample for the endpoint of https://api.bitfinex.com/v2/auth/r/wallets is as follows. This is from API reference.
Sample for the endpoint of https://api.bitfinex.com/v2/auth/r/wallets
request.post(
`${url}/auth/r/wallets`,
headers: { /* auth headers */ },
body: {},
json: true,
(error, response, body) => console.log(body)
)
When above points are reflected to your script, the modified script is as follows.
Modified script :
function wallet() {
var api_key = PropertiesService.getScriptProperties().getProperty('api_key');
var api_secret = PropertiesService.getScriptProperties().getProperty('api_secret');
var apiPath = "v2/auth/r/wallets";
var nonce = Date.now().toString();
var body = {};
var rawBody = JSON.stringify(body);
var signature = "/api/" + apiPath + nonce + rawBody;
signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, signature, api_secret)
.map(function(e) {
var v = (e < 0 ? e + 256 : e).toString(16);
return v.length == 1 ? "0" + v : v;
}).join("");
var url = "https://api.bitfinex.com/" + apiPath;
var options = {
method: 'POST',
contentType: "application/json",
headers: {
'bfx-nonce': nonce,
'bfx-apikey': api_key,
'bfx-signature': signature
},
payload: rawBody
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
Logger.log(result)
// var wallet_btc = result.BALANCE // I couldn't confirm whether this key exists.
}
References :
Sample scripts for Bitfinex API
API reference
UrlFetchApp.fetch()
I cannot confirm whether this works. If this didn't work, can you tell me the situation? I would like to modify.
Edit :
When you want 0.0957596 from the result of [["exchange", "USD", 14.81076629, 0, null], ["exchange", "BTC", 0.0957596, 0, null], ["funding", "BTC", 4.13E-6, 0, null], ["funding", "ETH", 3.50186961, 0, null], ["exchange", "OMG", 5.9E-7, 0, null]];, you can use the following script.
Script :
function wallet() {
var api_key = PropertiesService.getScriptProperties().getProperty('api_key');
var api_secret = PropertiesService.getScriptProperties().getProperty('api_secret');
var apiPath = "v2/auth/r/wallets";
var nonce = Date.now().toString();
var body = {};
var rawBody = JSON.stringify(body);
var signature = "/api/" + apiPath + nonce + rawBody;
signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, signature, api_secret)
.map(function(e) {
var v = (e < 0 ? e + 256 : e).toString(16);
return v.length == 1 ? "0" + v : v;
}).join("");
var url = "https://api.bitfinex.com/" + apiPath;
var options = {
method: 'POST',
contentType: "application/json",
headers: {
'bfx-nonce': nonce,
'bfx-apikey': api_key,
'bfx-signature': signature
},
payload: rawBody
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
// Logger.log(result)
// var wallet_btc = result.BALANCE // I couldn't confirm whether this key exists.
var balance = 0;
for (var i in result) {
if (result[i][0] == "exchange" && result[i][1] == "BTC") {
balance = result[i][2];
break;
}
}
Logger.log(balance)
}
Note :
From the document, it seems that the indexes of WALLET_TYPE, CURRENCY and BALANCE are always 0, 1 and 2 of each element in the response, respectively.