how can i get data from API using flutter? - json

I am new to flutter , I am creating an app and want to integrate JSON API in my application for Quran , Qibla and all things like this.
Kindly suggest me best API for this requirement and how i will be able to integrate this API in my App?
Future<Map> getNews() async {
String apiurl = "https://your url/";
http.Response response = await http.get(apiurl);
return json.decode(response.body);
}

You can get required API URLs by visiting relevant platforms like Al Quran for Quran. Here is an example URL for all the Surah in Quran. For Ahadith, you can get APIs from Sunah.com. Also, see a Sample App for what you are trying to create. You'll need to google stuff for each of your requirements and features.

Related

Api request in Swift

I want to use a recipe API for an app. I have registered and obtained a key for an API. However, I don't know where to put my key in the URL so I can paste it into the browser and get the JSON response.
This is the example Curl request
$response = Unirest\Request::get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false&ingredients=apples%2Cflour%2Csugar&limitLicense=false&number=5&ranking=1",
array(
"X-Mashape-Key" => "KEY",
"X-Mashape-Host" => "spoonacular-recipe-food-nutrition-v1.p.mashape.com"
)
);
This is what I get when I search the URL:
{
"message":"Missing Mashape application key. Go to http:\/\/docs.mashape.com\/api-keys to learn how to get your API application key."
}
If anyone knows how to create the full URL with the key or another way to get the Json response in Swift it would be really appreciated.
Thank you
If you want to call an API in Swift, I would recommend using the Alamofire library found here: https://github.com/Alamofire/Alamofire.
In order to authenticate to an API call you have to follow their documentation to find out how they want you to authenticate. Some services have no authentication, while others use a one time use token and some use an API key passed through the request header. It looks like this API call requires the key and host to be passed through the request header. Using Alamofire, the request would look something like this:
let headers: HTTPHeaders = [
"X-Mashape-Key": "KEY",
"X-Mashape-Host": "spoonacular-recipe-food-nutrition-v1.p.mashape.com"
]
Alamofire.request("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false&ingredients=apples%2Cflour%2Csugar&limitLicense=false&number=5&ranking=1", headers: headers).responseJSON { response in
debugPrint(response)
}
If you want to test API calls without coding the request in the app before hand, I would recommend downloading an application called Postman. This will allow you to test APIs and see their responses to help you in your swift app.

Twitter OAUTH Acces Token Response in JSON

I'm using Twitter's REST API to authorize an app. I just authorized the app with
https://api.twitter.com/oauth/authorize
and got an oauth_verifier from the redirect uri.
Then I just used
https://api.twitter.com/oauth/access_token
to get an access_token.
The problem is that the format of response I got from this method is text/plain. It's just like
oauth_token=783897656863051776-5hQfcJTv4FzFpPcyVRbnjPUbJXR29&oauth_token_secret=MViTPOOCaHNZrW6HTIFZ340bq1rutJKL8oqkBxRp2aiW&user_id=783897656863051776&screen_name=sWest&x_auth_expires=0
My query is that how to get the response in application/json format.
Any help will be appreciated !!!
You will need to parse it like application/x-www-form-urlencoded content, any language with HTTP Client libraries should provide this functionality. But it isn't clear what language and libraries you are using.
This example uses joauth library to parse
protected static Map<String, String> parseTokenMap(String tokenDetails) {
KeyValueHandler.SingleKeyValueHandler handler =
new KeyValueHandler.SingleKeyValueHandler();
KeyValueParser.StandardKeyValueParser bodyParser =
new KeyValueParser.StandardKeyValueParser("&", "=");
bodyParser.parse(tokenDetails, Collections.singletonList(handler));
return handler.toMap();
}

Other technologies that can perform DTO request response like WCF

I have a WCF service that allows me make a request using an DTO and replies with a DTO for a WPF application. For example I pass a filter object for products which has a few properties for things I want to filter on and a couple of extras for paging, (the server will take care processing the filter object and getting the data) an example is like this.
public async Task<ObservableCollection<ProductListItem>> GetProductList(ProductFilter filter, int startIndex, int pageSize, string sortBy)
I am wondering if there exists any other technologies beside WCF that allow such an operation, From my preliminary research which may be quite off is that WebAPI uses the GET, POST, PUT verbs and routing rules which is quite different.
ServiceStack looks like it might be able to do this I can see on slide 37 at https://servicestack.net/features
it says.
List<Product> productOver2Bucks = client.Get(new FindProducts{PriceGreaterThan = 2})
Which seems pretty close but might still require Rest verbs as it uses a Get().
I don't know it it is FUD or not but I have been reading that soap over WCF is believed by some to be a legacy technology and JSON is the way of the future. So is there a replacement technology that will work with a method signature to the one I have above? That i could call from platforms such as Windows universal applications.
In ServiceStack if you design your Service with the Any method name, e.g
public object Any(Request request)
{
return new Response { ... };
}
This will allow calling this Service from Any HTTP Verb on any Format or endpoint (e.g. JSON, XML, MsgPack, Protocol Buffers, SOAP, Message Queue's, etc).
Also you don't need to define any [Route] for your Request DTO's since it will automatically fallback into using the pre-defined Routes when none are available.
public class Request : IReturn<Response> { ... }
public class Response { }
So with the above Service you can use ServiceStack .NET ServiceClients to call the API's using any verb, e.g:
var client = new JsonServiceClient(baseUrl);
Response response = client.Get(new Request { ... });
Response response = client.Post(new Request { ... });
When preferred you can also use the async API's, e.g:
var response = await client.GetAsync(new Request { ... });
var response = await client.PostAsync(new Request { ... });
Which if you don't care for using verbs you can use the generic Send API, e.g:
Response response = client.Send(new Request { ... });
Which just uses POST underneath, although it's highly recommended to use Get for "read only" queries as it will allow the Services HTTP responses to be cached by any intermediate HTTP Middleware or proxies.
Add ServiceStack Reference
Also if you're coming from WCF you'll also enjoy ServiceStack's, Add ServiceStack Reference which provides a number of advantages over WCF's Add Service Reference feature but still provides the same utility in being able to generate a typed API from a remote url for:
C# Add Reference
F# Add Reference
VB.NET Add Reference
TypeScript Add Reference
With more languages to follow.
Advantages over SOAP
Whilst ServiceStack still enables WSDL's, XSD's for your Services so they can be called from SOAP 1.1/1.2 endpoints for legacy compatible reasons - there are a number of reasons why using clean HTTP and JSON/XML API's are preferred.

Using xamarin to retrieve JSON message from URl and show in table view

I'm started developement in xamarin cross platform development in visual studio. I want to know, how to retrieve the JSON message from url to show the details in table view. Here i give a sample url, how to retrieve all the city name in the json data and show in table. Help me!
url: http://api.wunderground.com/api/02e5dd8c34e3e657/geolookup/conditions/forecast/q/Dhaka,Bangladesh.json
As #Udi said, your question is too broad. But because of that, I'll give broad answers.
First, use HttpClient to retrieve the data from your url. Second, use Json.Net to deserialize your response into your entities/model.
string url = #"http://api.wunderground.com/api/02e5dd8c34e3e657/geolookup/conditions/forecast/q/Dhaka,Bangladesh.json";
using (var client = new HttpClient())
{
var result = await client.GetStringAsync(url);
return JsonConvert.DeserializeObject<YourModelForTheResponse>(result);
}
Third, to display your data, I would suggest going Xamarin.Forms or MonoTouch.Dialog. It makes using tables way easier.
I have a sample app that I queried a service, got a json response, and displayed the list of data using both Xamarin.Forms and MonoTouch.Dialog. Check out my sample app at github.
I posted this question on xamarin forums with complete coding. I got a answer from someone with complete coding structure. Its work for me.
click here to see the link with question and answer. I hope, it works for all u.

Generate PDF document with data on Titanium DB

I am creating a mobile app using Titanium. I am using the titanium db which is sqlite. This pdf needs to have boxes to structure the data and images that I am taking with the app as well.
I am assuming what I need to do is convert the data into json on titanium, upload it to a web server and insert into a mysql/phpmysql db and then use some sort of script that is out there will read the web db and create a pdf and send it back to the phone
is that right?
and if so...i need help with that whole process haha...any good tutorials on db upload to web db process?
Check the docs, HTTPClient is what you need to use, its a standard.
First steps would be to create a web service on your server that parses your JSON formatting. The bulk of the work you would have to do has nothing to do with Titanium, but here is the code for sending a JSON object to some web service with a POST from a Titanium App.
var xhr_getstep = Titanium.Network.createHTTPClient();
xhr_getstep.onload = function(e) {
// Do something with the response from the server
var responseBlob = this.responseText;
};
xhr_getstep.onerror = function() {
Ti.API.info('[ERROR] WebService failed.');
};
xhr_getstep.open("POST", 'http://yourwebsite.com/yourwebserviceentry.php');
xhr_getstep.setRequestHeader("Content-Type", "application/json");
// Create your object with info on how to create the PDF
var objSend = {title : 'Amazing Title'};
xhr_getstep.send(obj); // Send it all off