How to make api call of string in flutter? - api

I am learning Flutter. This is the string that I need to call and I don't know how to call this type of string.
{
"Info":[
{
"c_type_id":"1",
"cleaning type":"Washroom Cleaning"
},
{
"c_type_id":"2",
"cleaning type":"Garden\/Lawn Cleaning"
}
]
}
My code
class Album {
final String title;
Album({
this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
title: json['title'],
);
}
}
As I am following my code like this https://flutter.dev/docs/cookbook/networking/fetch-data
and got this error "A non-null String must be provided to a Text widget." because they are following this type of string and my string type is different. Help!
{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim"
}

Your given data (API response) seems to have a list of maps, so you should get the data first (use async function):
var response = await http.get("Your Url")
then you should extract the given map list as follow:
var temp = json.decode(response);
List<dynamic> result = temp['Info']); // it is the described list
now, you can use your data (extract each parameter):
String c_type_id = result[0]['c_type_id'];
// and so on...

Your question is not clear at all but I can show you an example how to reach an element in a json.
Your json consists a list that contains string keys. To reach first element of list;
json["Info"][0]
Then pass the key you want to get its value;
json["Info"][0]["c_type_id"]
http_requests All type of http requests are mentioned in this post. If you have any further problem kindly make comment.

Related

How do I pass a json body request to api in a map string data structure in Golang?

I am new to golang and grpc, need guidance and clarification. I have below definition as a parameter to call a POST request for an external API.
params := map[string]string{
"movie": movie,
"seat": seat,
"pax": fmt.Sprint(pax),
"class": class,
}
In proto file, I have below:
message TicketData {
string movie= 1;
string seat= 2;
uint32 pax= 3;
string class = 4;
}
message SearchMovieRequest {
TicketData data= 1;
}
However in POSTMAN (grpc request), the body request is showing below:
{
"data":
{
"movie": "abc",
"seat": "123",
"pax": 2,
"class ": "b""
}
}
the request body should be below:
{
"data": **[**
{
"movie": "abc",
"seat": "123",
"pax": 2,
"class ": "b""
}
**]** - missing brackets in my json body
}
I have tried using structpb and also map string interface. It doesn't seem to work. Any pointer will be appreciated. Thank you.
You want the data field to be repeated TicketData.
See e.g. Specifying Field Rules in the Protobuf Language Guide (proto3).
Specifically:
message TicketData {
string movie= 1;
string seat= 2;
uint32 pax= 3;
string class = 4;
}
message SearchMovieRequest {
repeated TicketData data= 1;
}
NOTE Although you include protobuf definitions, your examples are JSON. Protobuf implementations usually include automatic mappings between protobuf and JSON which is -- I assume -- what you're presenting.

How to do an API call with Future and Uri.Https constructor in Flutter

Trying to build a Recipe App using Spoonacular API. Tried googling for answers but it seems like there was a change in uri.https format and all of the search results are from last year and older. I can't figure out the correct format for this? This is my first time calling APIs in flutter and I can't seem to get it right.
Here's the tutorial: https://youtu.be/l3CIMZSAaIk
And here's the source code: https://github.com/MarcusNg/flutter_recipe_app
This link shows how to generate a meal plan:
https://spoonacular.com/food-api/docs#Generate-Meal-Plan
Here's how I'm trying to call it in URL form:
https://api.spoonacular.com/mealplanner/generate?apiKey=[CHANGE_THIS_TO_APIKEY]&timeFrame=day&1700&vegan
This works perfectly in the browser and I need to convert it to flutter code:
class APIservice {
APIservice._instantiate();
static final APIservice instance = APIservice._instantiate();
final String _baseUrl = 'api.spoonacular.com';
static const String API_KEY = '[APIKEY HERE]';
//Generate Meal Plan
Future<MealPlan> generateMealPlan({int targetCalories, String diet}) async {
if (diet == 'None') diet = '';
Map<String, String> parameters = {
'apiKey': API_KEY,
'timeFrame': 'day',
'targetCalories': targetCalories.toString(),
'diet': diet,
};
Uri uri = Uri.https(
_baseUrl,
'/mealplanner/generate',
parameters,
);
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: 'application/json',
};
try {
var response = await http.get(uri, headers: headers);
Map<String, dynamic> data = json.decode(response.body);
MealPlan mealPlan = MealPlan.fromMap(data);
return mealPlan;
} catch (err) {
throw err.toString();
}
}
When I run the app I get the error below:
E/flutter ( 6458): [ERROR:flutter/lib/ui/ui_dart_state.cc(171)] Unhandled Exception: Invalid argument(s)
[38;5;248mE/flutter ( 6458): #0 APIservice.generateMealPlan [39;49m
E/flutter ( 6458):
It looks like it's having problems piecing the parameters to turn into URL. I'm not sure if I wrote the MAP parameters and URI format correctly though.
The issue was with the Meal model. The Meal model you had was different from what the api was returning:
I fixed the Meal model, check the code below:
class Meal {
int id;
String imageType;
String title;
int readyInMinutes;
int servings;
String sourceUrl;
Meal(
{this.id,
this.imageType,
this.title,
this.readyInMinutes,
this.servings,
this.sourceUrl});
Meal.fromMap(Map<String, dynamic> json) {
id = json['id'];
imageType = json['imageType'];
title = json['title'];
readyInMinutes = json['readyInMinutes'];
servings = json['servings'];
sourceUrl = json['sourceUrl'];
}
}
For some reasons, looks like the api doesn't really provide adequate support for the respective images, some images link are broken.
The app result looks like below:

type 'String' is not a subtype of type 'Null' in get method flutter

I got this error: type 'String' is not a subtype of type 'Null' in get method flutter
this is the get api function that i use
Future<Stream<ServiceTypes>> getServiceTypesa() async {
final String url = 'https://test.com';
final client = new http.Client();
final streamedRest = await client.send(
http.Request('get', Uri.parse(url))
);
return streamedRest.stream
.transform(utf8.decoder)
.transform(json.decoder)
.expand((data) => (data as List))
.map((data) => ServiceTypes.fromJson(data));
}
you can see here the function detect the data
i saw also this error
StateError (Bad state: Stream has already been listened to.)
and this error
this is my listen function
#override
void initState() {
_serviceTypes = new List<ServiceTypes>();
listenForServiceTypes();
super.initState();
}
void listenForServiceTypes() async {
setState(() {
this._show_serviceTypesProgress = true;
});
final Stream<ServiceTypes> stream = await getServiceTypesa();
stream.listen((ServiceTypes serviceTypes) =>
setState(() => _serviceTypes.add(serviceTypes)));
setState(() {
this._show_serviceTypesProgress = false;
});
print(_serviceTypes);
}
this is the model that i made
I don't know what is the problem because the print function return : []
When you create model, the image type value is null so, the model is create with Null type of image but when images are not null type from server then it gives you an error
type 'String' is not a subtype of type 'Null' in get method flutter
because your image type is String from server and you get value by Null Object, So use String type object for getting string value or images.
Use this
Class ServiceTypes{
String image;
instead of
Class ServiceTypes{
Null image;
As extra information, you can check the keys name. I faced the same problem just because I tried to fetch a key not found.
In the first time I wrote content instead of details and in my API I have details not content.
have a good day :)
The issue is clear, you define image type as Null then trying to pass string to it, try to change definition.. like so:
Class ServiceTypes{
int id;
String name;
String image;
...
use ? this for nullable key. For example :
final String? title;
final String? category;
here is the complete solution :
Is it possible to parse json in Flutter/Dart with missing attributes (keys of json data)?

How to print SearchRequest

I'm trying to validate filter generation logic, so I have an instance of SearchRequest, but how to get a String representation of it ?
I don't have SearchResponse, only SearchRequest since I'm simply capturing it in my test.
This doesn't compile "Can't convert from NestSearchRequest" to byte[].
This doesn't work either, there is no Client class in Nest and ElasticClient doesn't have Serializer property (Nest 1.6.0/Elasticsearch 1.6.1).
Here's a complete example for how to get the json representation of a query, using NEST 1.6.0
void Main()
{
var client = new ElasticClient(connection: new InMemoryConnection());
var query = Query<Document>.Match(m => m
.OnField(f => f.Name)
.Query("Match This Name")
);
var json = Encoding.UTF8.GetString(client.Serializer.Serialize(query));
Console.WriteLine(json);
}
public class Document
{
public string Name { get; set; }
}
which prints the following to the console
{
"match": {
"name": {
"query": "Match This Name"
}
}
}

Customize binding in ASP.NET Web Api

I am stuck with following problem in ASP.NET Web Api. Let say I have following code in my ApiController:
public void Post(Person person)
{
// Handle the argument
}
What I would like to do is to accept following JSON request:
{
"person": {
"name": "John Doe",
"age": 27
}
}
I would like to go around creating some holding object for each model just to properly bind incoming data. In previous version of MVC, it was possible to define something like Prefix to solve this.
Let me report that I have been able to solve this implementing CustomJsonMediaTypeFormatter:
public class EmberJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(
Type type,
System.IO.Stream readStream,
System.Net.Http.HttpContent content,
IFormatterLogger formatterLogger)
{
return base.ReadFromStreamAsync(
typeof(JObject),
readStream,
content,
formatterLogger).ContinueWith<object>((task) =>
{
var data = task.Result as JObject;
var prefix= type.Name.ToLower();
if (data[prefix] == null)
{
return GetDefaultValueForType(type);
}
var serializer = JsonSerializer.Create(SerializerSettings);
return data[prefix].ToObject(type, serializer);
});
}
}
and replacing default JsonMediaTypeFormatter in GlobalConfiguration.