I want to send an HTTP GET request with json body using dart. I know this is possible, because I've done it in the past but can't find the files/recode it. Packages like dart:http doesn't allow to send a body along with an GET request.
thanks for help
I am not really sure where the problem should be but I have made this example for Dart VM which I guess does what you want:
import 'dart:convert';
import 'dart:io';
Future<void> main(List arguments) async {
final response =
await getCallWithBody('http://localhost:8080', {"Key": "Value"});
response.forEach(print);
}
Future<List<String>> getCallWithBody(String address, Object object) async {
final client = HttpClient();
final request = await client.getUrl(Uri.parse(address));
request.contentLength = -1;
request.add(utf8.encode(json.encode(object)));
await request.flush();
return (await request.close())
.transform(utf8.decoder)
.transform(const LineSplitter())
.toList();
}
Related
I'd like to download the JSON file which can be accessed by this url https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media. Unfortunately I was not able to download this file with the http get-function. I assume that I have some problem with the parsing since if I remove "?alt=media" it works perfectly, but unfortunately I only get the meta-json file. This is the code which I use:
import 'package:http/http.dart' as http;
[...]
[...]
void testFunction(){
var url_string = "https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media";
var result = await getJsonFromFirebaseRestAPI(url_string);
print(result);
}
Future<String> getJsonFromFirebaseRestAPI(String url) async {
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
The JSON file result should look like this:
routes: []
It's basically empty I'm just trying to implement the function.
I use http: ^0.13.5
I get the following error:
Error: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 299:10
createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 341:28
_throw
dart-sdk/lib/core/errors.dart 116:5
throwWithStackTrace
dart-sdk/lib/async/zone.dart 1378:11
callback
dart-sdk/lib/async/schedule_microtask.dart 40:11
_microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5
_startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15
<fn>
Can anybody solve my issue?
Appreciate your time :)
I did few changes on your code and it is working. There was no issue with the get function. here is the updated piece
import 'package:http/http.dart' as http;
// just a normal main to test the function in terminal
void main(List<String> arguments) async {
await testFunction();
}
// changed this to future and made it async
Future<void> testFunction() async {
var url_string = "https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media";
var result = await getJsonFromFirebaseRestAPI(url_string);
print(result);
}
// no changes applied here.
Future<String> getJsonFromFirebaseRestAPI(String url) async {
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
I am using Dart Shelf framework for building an API. Get works fine but I am having issues with post. I couldn't access any of the body parameters of the post request in my server. Here is what I have tried.
// shelf-router
router.post('/login', (Request req) async {
final body = await req.readAsString();
// to check
print(body); // outputs null
return
Response.ok('OK');
});
How am I testing this?
Using postman with the endpoint and body type raw (JSON).
payload as
{
"user":"testUser",
"password":"p455w0rd"
}
I even tried setting contenttype header to application/JSON but no luck there too.
Try this inside your request handler function..
final String query = await request.readAsString();
Map queryParams = Uri(query: query).queryParameters;
print(queryParams);
final String query = await request.readAsString();
// Map<String, String> queryParams = Uri(query: query).queryParameters;
Map queryParams = jsonDecode(query);
print(queryParams['user']);
I can receive the parameter from the postman with form-data.
I am using shelf_route in the server.
If this is similar to you, you can follow this:
https://stackoverflow.com/a/74255231/17798537
I managed to load the data from a Json File which is local on my Flutter Project. I also was able to fetch Data from the Internet, if the API Url was like:
https://[API-Server][parameter1:xy][parameter2:abc][API-KEY:lasgoewrijeowfjsdfdfiia]
I archieved that with this code sample:
Future<String> _loadStringFixtures() async {
return await rootBundle.loadString('assets/fixtures.json');
}
Future loadFixtures() async {
String jsonString = await _loadStringFixtures();
final jsonResponse = json.decode(jsonString);
FixturesAPI value = new FixturesAPI.fromJson(jsonResponse);
return value;
}
So far so good...
But now I am facing a problem with the API Provider RapidAPI
You can find the documentation etc. here:
https://rapidapi.com/api-sports/api/api-football/endpoints
As you can see they give some code snippets to connect to their API.
There are some for C, C#, Java, Python etc. You can look into all of them with the link above.
Sadly there is no example for Flutter.
And I do not see a way to adapt these examples.
Normally you can paste your API Key directly into the URL, but this seems not possible here? Or maybe it is?
Does Flutter also have other possibilities to receive data from an API besides the one I did?
Thank you so much in advance for your help!
It's possible to with http package and very easy. You can see in this example below...
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class APIService {
// API key
static const _api_key = <YOU-API-KEY-HERE>;
// Base API url
static const String _baseUrl = "api-football-beta.p.rapidapi.com";
// Base headers for Response url
static const Map<String, String> _headers = {
"content-type": "application/json",
"x-rapidapi-host": "api-football-beta.p.rapidapi.com",
"x-rapidapi-key": _api_key,
};
// Base API request to get response
Future<dynamic> get({
#required String endpoint,
#required Map<String, String> query,
}) async {
Uri uri = Uri.https(_baseUrl, endpoint, query);
final response = await http.get(uri, headers: _headers);
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
return json.decode(response.body);
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load json data');
}
}
}
Then get you request:
//....
APIService apiService = APIService();
// You future
Future future;
//in the initState() or use it how you want...
future = apiService.get(endpoint:'/fixtures', query:{"live": "all"});
//....
Yes it possible in flutter. Use the Dio Package in flutter which is a powerful Http client. Using dio you can set interceptors to add api key to url so you don't have to append it in every request. Setting interceptors will help you.
Is it possible to Stream an REST API JSON response with Dart?
Ex. Response size is 5000 lines. I would like to read it line by line without first loading the whole response from the source.
I think something similar is possible with Java and JavaScript.
With the http package, you can use the send() method to send the request and have a Stream with the response.
With Utf8Decoder and LineSplitter from dart:convert, you can decode and read each line as you receive it.
import 'dart:convert';
import 'package:http/http.dart';
main() async {
var request = Request('GET', Uri.parse('http://localhost:8090'));
var response = await request.send();
var lineStream =
response.stream.transform(Utf8Decoder()).transform(LineSplitter());
// lineStream is a Stream<String> with each line from the response as an event.
// We can use the listen() method or await for to read it.
await for (String line in lineStream) {
print(line);
}
}
I'm making an app that grabs cryptocurrency JSON data from the public v1 Api but support for this will soon be dropped, meaning that I'll have to migrate the the more powerful professional v1 Api.
The only issue is, I don't know how to implement the use of the new Api key thats required as I parse the JSON data.
I'm using a heavily modified version of this git repo to program the app, but all basic functionality is based here.
All I need is guidance on what I need to add to this file to display the new professional v1 Api, any comments or ideas are appreciated. Thanks
This the the crypto_data_prod.dart file where I would have to change my code for use with the key.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:fluttercrypto/data/crypto_data.dart';
class ProdCryptoRepository implements CryptoRepository {
String cryptoUrl = "https://api.coinmarketcap.com/v1/ticker/?limit=50";
#override
Future<List<Crypto>> fetchCurrencies() async {
// TODO: implement fetchCurrencies
http.Response response = await http.get(cryptoUrl);
final List responseBody = JSON.decode(response.body);
final statusCode = response.statusCode;
if (statusCode != 200 || responseBody == null) {
throw new FetchDataException(
"An error ocurred : [Status Code : $statusCode]");
}
return responseBody.map((c) => new Crypto.fromMap(c)).toList();
}
}
Try to change http.Response response = await http.get(cryptoUrl); to
http.Response response = await http.get(cryptoUrl,
headers: {"X-CMC_PRO_API_KEY": "cab79c7b-52e9-4e4b-94fc-b0f32da14799"});
For more info check this link.