Lecture 13 (APIs)
Lecture 13 (APIs)
The services.dart as rootBundle contains the resources that were packaged with the application when it
was built. To add resources to the rootBundle for your application, add them to the assets subsection of
the flutter section of your application's pubspec.yaml manifest.
Chrome “JSON Viewer Awesome” Plugin
This plugin shows json data in JSON format on chrome browser.
if (response.statusCode == 200) {
// If the server returns an OK response, then parse the JSON.
return Post.fromJson(json.decode(response.body));
} else {
// If the response was umexpected, throw an error.
throw Exception('Failed to load post');
}
}
try {
http.Response response = await http.get(uri);
print(response.statusCode);
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
String data = jsonData[0]['name'].toString();
print(data); // = Leanne Graham
} else {
throw Exception('Unable to fetch products from the REST API');
}
}catch(e){
print("exception is $e");
}
}
IT Industry-Academia Bridge Program
Getting the response code and body
Get the response body
• response.body
Get the resoonse code
• response.statusCode
shelf_router makes it easy to build web applications in Dart by composing request handlers.
To add package
dependencies:
shelf_router: ^1.1.3
Import Package as
import 'package:shelf_router/shelf_router.dart';
Another pakcage name “shelf” can also be used to makes it easy to create and compose web
servers and parts of web servers.
Example-1
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart'; #dart run dartapiserver
import 'package:shelf/shelf_io.dart' as io;
Browser
void main() async { http://localhost:4040
final app = Router(); Hello World
app.get('/', (Request request) { http://localhost:4040/hello
return Response.ok('Hello World'); Hello World hello
});
app.get('/hello', (Request request) {
return Response.ok('Hello World hello');
});
await io.serve(app, 'localhost', 4040);
}
IT Industry-Academia Bridge Program
{
"users":[
users.json
Example-2
{
"id":1,
"Name":"Rachel Green",
"Age": 32
(json handler) },
{
"id":2,
"Name":"Ross Geller",
import 'package:shelf_router/shelf_router.dart'; "Age": 33
},
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io; ]
import 'dart:io'; }
import 'dart:convert';