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'];
Related
var res = await http.get(Uri.parse("SomeEndPoint"));
var data1 = jsonDecode(res.body);
this is my code what next i do to use it in flutter app
Well, you can get all the information in the data, for example:
final data = jsonDecode(res.body);
// For example this data looks like this:
// {
// "id": "hZs68Hs7u",
// "message": "Hello",
// }
Now you can access the fields in it and do whatever you want:
final String id = data["id"];
final String message = data["message"];
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;
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
If I hard code the band name in my client request with RestSharp I get the results I expect. If I pass in the String I get a different result set. I checked the url it formed and they are the same. Any ideas? I don't use both, I will comment one out and use the other for testing this scenario.
ArtistInfoResponse IMusicRepository.GetArtistResponse(string artistName)
{
var client = new RestClient($"https://api.deezer.com/search?q=artist:{artistName}");
// returns this as url https://localhost:44343/Home/ArtistInformation?artistName=Dave%20Matthews%20Band
var client = new RestClient($"https://api.deezer.com/search?q=artist:\"Dave Matthews Band\"");
// returns this in url https://localhost:44343/Home/ArtistInformation?artistName=Dave%20Matthews%20Band
var request = new RestRequest(Method.GET);
var cancellationTokenSource = new CancellationTokenSource();
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
// Deserialize the string content into JToken object
var content = JsonConvert.DeserializeObject<JToken>(response.Content);
// Deserialize the JToken object into our ArtistInfoResponse Class
return content.ToObject<ArtistInfoResponse>();
}
return null;
}
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];