Array of strings in an API call, - json

Correct Answer below.
I want to select products by bulk instead of making individual product calls, but I'm just messing up the syntax and can't get the right combination even with all the answers here that I have read.
I am creating a list of product codes but keep getting back 404 or 405 error code
Instructions:
/products/bulk
productCodes
required
Array of strings <= 500 items
List of product codes for which to retrieve full product details
Request sample:
{
"productCodes": [
"5010SYDNEY",
"2050_PA",
"2855KENNEDY_TKTS"
]
}
My code:
// Product codes
const List productCodes = [
'58109P2', '127269P1',
'127269P1', '250556P1', '204123P16',
];
try {
var response = await http.post(
Uri.parse("https://api.viator.com/partner/products/bulk?$productCodes"),
headers: headers);
if (response.statusCode == 200) {
var jsonData = json.decode(response.body);
print(jsonData);
}else{
print(response.statusCode);
}catch (e) {
print(e);
}
Access is fine, I connect and can get the results back for a single product but it's the Array on string in the query that has me confused.
Thanks

A couple of changes to get the page to load. The product codes have to be in a string
var productCodes =
'{"productCodes": ["58109P2","127269P1","250556P1"]}';
Then add them to a post call
var url = Uri.parse('https://api.viator.com/partner/products/bulk');
var response = await http.post(url, headers: headers, body: productCodes);
The response then will have an instance of the object

Related

Forge Model Derivatives: GET metadata always returns 202

I'm trying to get the Derivative Tree Json view of a large file in nwd format, but it always responds with the status code 202:
{"result":"success"}
My objective is to get the dbids of the first level of the tree with its name. If this works, it would be to get their properties via {urn}/metadata/{modelGuid}/properties
RestClient client = new RestClient("https://developer.api.autodesk.com");
RestRequest request = new RestRequest("/modelderivative/v2/designdata/{urn}/metadata/{modelGuid}", Method.Get);
request.AddHeader("Authorization", "Bearer " + authenticate.access_token);
//request.AddHeader("x-ads-force", true);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("urn", urn, ParameterType.UrlSegment);
request.AddParameter("modelGuid", guid, ParameterType.UrlSegment);
request.AddParameter("forceget", true, ParameterType.QueryString);
request.AddParameter("objectid", 1, ParameterType.QueryString);
request.AddParameter("level", 1, ParameterType.QueryString);
var response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
var result = response.Content;
}
Who can help?
Thanks
According to the documentation Fetch Object Tree, the status code 202 means : "Request accepted but processing not complete. Call this endpoint iteratively until a 200 is returned."
It seems pretty normal if you are working with a large model. But you should be able to get the 200 response after waiting some time.
Appending what Alex said, you can use do-while to check if the response code is 200.
ApiResponse<dynamic> treeRes = null;
do
{
treeRes = await // Your API reqeust here
if (treeRes == null) throw new InvalidOperationException('Failed to get tree');
if (treeRes.StatusCode != 200)
System.Threading.Thread.Sleep(60 * 1000);
}
while (treeRes.StatusCode != 200);
var properties = treeRes.Data;

Flutter - Multiple HTTP Requests to the same JSON

I have this API where go to fetch data.
For each "date" I have a JSON Object.
What I want to do is fetch objects from let's say 5 years and get them on the same final JSON http response.
So I don't have to display only a day at the time.
Future<List<Schedule>> getFromEspnSchedule(String sport) async {
final url = 'http://myserver.com/api/$date'; //the $date would be e.g. 2010, 2011, 2012, ...
final response = await http.get(url);
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((data) {
return new Schedule.fromJson(data);
}).toList();
}
}
What is the best way to implement this?
If your API returns just a single Schedule object, you need to modify your method to get a single element.
Future<Schedule> getFromEspnSchedule(String sport) async {
final url = 'http://myserver.com/api/$date';
final response = await http.get(url);
if (response.statusCode == 200) {
return Schedule.fromJson(json.decode(response.body));
} else {
// make sure you return API error here
}
}
After you do this, you can go ahead and chain this into multiple calls made at the same time to achieve getting the data faster:
List<Schedule> responseList = await Future.wait([
getFromEspnSchedule('football'),
getFromEspnSchedule('volleyball'),
getFromEspnSchedule('basketball'),
getFromEspnSchedule('chess'),
]);
// responseList objects are listed the same way they are called above.
Schedule footballSchedule = responseList[0];
Schedule volleyballSchedule = responseList[1];
Schedule basketballSchedule = responseList[2];
Schedule chessSchedule = responseList[3];

how to store json response locally (sqflite database) in flutter

I did not able to store json response from API in sqflite database but i already parsed json response in list and also i stored similar data in sqflite database.
To stored locally i got success and able to perform CRUD operation and sending it to server, similarly i also able to perform CRUD operation on API data but problem arises on synchronization between local and json data.
the below code id for calling json data
Future<List<Activities>> getData() async {
List<Activities> list;
var res = await http
.post("http://xxxx/get-activity", headers: {
HttpHeaders.authorizationHeader: "Bearer " + _token.toString()
});
if (res.statusCode == 200) {
var data = json.decode(res.body);
var rest = data["data"] as List;
// print(rest);
list = rest.map<Activities>((json) => Activities.fromJson(json)).toList();
// print('okay, ${rest[0]}!');
} else {
print('something error');
}
print("List Size: ${list.length}");
return list;
}
solved
var data = json.decode(res.body);
var activities= data["data"] as List;
for (var activity in activities) {
Activity actData = Activity.fromMap(activity);
batch.insert(actTable, actData.toMap());
}
Solution! Please use this flutter plugin json_store

How to fetch api data by passing variables (parameters)?

I am fetching api data for sports player for which I need to pass unique player id. Currently, I have to pass pid manually which fetches only one player's data at a time. But I would like to fetch multiple players data and display it in listView.
API endpoint is: https://cricapi.com/api/playerStats?apikey=&pid=0000.
I am able to parse above url, fetch it's result and display in UI properly, but I want to fetch multiple players data and not just one.
Code to fetch api:
FetchJson() async {
var response = await http.get('https://cricapi.com/api/playerStats?
apikey=&pid=1111');
if (response.statusCode == 200) {
String responseBody = response.body;
var responseJson = jsonDecode(responseBody);
name = responseJson['name'];
playingRole = responseJson['playingRole'];
battingStyle = responseJson['battingStyle'];
country = responseJson['country'];
imageURL = responseJson['imageURL'];
Json snippet is:
{
"pid": 1111,
"country": "Australia",
"profile": "\n\n blah",
"imageURL": "https://www.cricapi.com/playerpic/1111.jpg",
What I am trying to achieve is, to display multiple players profile dynamically instead of passing hardcoded pid in the code, so that the UI will display multiple players in listview.
How to pass different pid dynamically in the url endpoint ?
By using String interpolation and receiving the id as parameter. You can read more about it here.
FetchJson(int playerId) async {
var response = await http.get('https://cricapi.com/api/playerStats?
apikey=&pid=$playerId');
if (response.statusCode == 200) {
String responseBody = response.body;
var responseJson = jsonDecode(responseBody);
name = responseJson['name'];
playingRole = responseJson['playingRole'];
battingStyle = responseJson['battingStyle'];
country = responseJson['country'];
imageURL = responseJson['imageURL'];

flutter:how can i received value as same as mysql database?

Hi I am try use mysql database in my flutter app...but till now fetch all data as string..what changes i have to done in my below code to received as data as my database...
in below code verify is a number and i want to received as number till time i received verify as string ....please help me ............
FetchJSON() async {
var Response = await http.get(
"http://192.168.42.107/my_payment/getdata.php",
headers: {"Accept": "application/json"},
);
if (Response.statusCode == 200) {
String responseBody = Response.body;
var responseJSON = json.decode(responseBody);
abc = responseJSON['username'];
verify = responseJSON['verified'];
setState(() {
print('UI Updated');
});
} else {
print('Something went wrong. \nResponse Code : ${Response.statusCode}');
}
}
So essentially you want "strongly typed" data for your http response, you have to define such data yourself. Normally people do something like this:
class MyData {
final String username;
final bool verified; // assume this should be a boolean
MyData.fromJson(dynamic json)
: username = json['username'],
verified = json['verified'] == 1; // assume you get back a number for verified
}
Then you can convert your responseJSON to MyData and carry on from there.