0% found this document useful (0 votes)
11 views42 pages

Lecture 13 (APIs)

The document provides an overview of APIs, focusing on REST and SOAP architectures, and the use of JSON for data interchange. It details the HTTP methods available in the Dart and Flutter http package for making network requests, along with examples of fetching and displaying data. Additionally, it covers the creation of a Dart server and the use of the shelf_router package for building web applications.

Uploaded by

Hasaan Bin Arif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views42 pages

Lecture 13 (APIs)

The document provides an overview of APIs, focusing on REST and SOAP architectures, and the use of JSON for data interchange. It details the HTTP methods available in the Dart and Flutter http package for making network requests, along with examples of fetching and displaying data. Additionally, it covers the creation of a Dart server and the use of the shelf_router package for building web applications.

Uploaded by

Hasaan Bin Arif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

APIs

IT Industry-Academia Bridge Program


API (Application Program Interface)

An API is a set of


routines, protocols,
and tools for building
software applications.
You must have API
Keys.

IT Industry-Academia Bridge Program


APIs architecture based on REST or SOAP
SOAP (Simple Object Access Protocol):
• Web Communication Protocol
• Work with HTTP, UDP, and SMTP
• Cannot cached and follow strict guideline.
• Has built-in security, error handling, and authorization.
• For communication, XML data format is used.

REST (Representation State Transfer):


• Work only with HTTP
• Request can be Cached.
• Developer have to take care of security, error handling, and authorization themselves.
• For communication, JSON, XML, HTML and plain Text format is used.
• Use for high performance, scalability, and flexibility.
Rest API
REST is the most popular approach to building web APIs, representing
over 70% of public APIs.
With the REST architecture, HTTP can receive requests on GET, POST,
PUT PATCH, HEAD, DELETE.
On Client-Side, HTTP request for REST API, made by open source
networking packages like Http (basic), Dio (best feature), Chopper,
Retrofit etc.

IT Industry-Academia Bridge Program


JSON Schema
JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and
transporting data. JSON data consist in name/value pairs, separated by commas , covered
by Curly braces
{"firstName":"John", "lastName":"Doe"}
It can be build in two structure
Objects:- A collection of name/value pairs, consist on open and close braces { }
Example: {"firstName":"John", "lastName":"Doe"}
In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
Arrays:- JSON data consist on open and close bracket [ object, object …]
Example [{"firstName":"John", "lastName":"Doe"}, {"firstName":"John", "lastName":"Doe"}]
In most languages, this is realized as an array, vector, list, or sequence.
A human-readable JSON format is an open standard for exchanging data on the web and more
lightweight than XML, easier to parse, and works with all programming languages.
It supports int, float, boolean, string, null, date data-types
JSON
JSON Array of Objects: JSON Array containing many JSON objects in it,
then we can iterate over that array or use the [ ] to get the object we
need.
{ "books":[
{"name":"Let Us C", "author":"Yashavant Kanetkar"},
{"name":"Rich Dad Poor Dad", "author":"Robert Kiyosaki "},
{"name":"Introduction to Algorithms", "author":"Cormen"},
]
}
 JSON data in [] access through index number start from zero
 JSON data in {} access through key
JSON Examples
var data = { "books": {"name":"Let Us C", "author":"Yashavant Kanetkar"}, };
How to Access book name value? var jsonData = data[‘books’][‘name’];
print(jsonData.toString());
Ans= ‘Let Us C’

How to access book auther? var jsonData = data[‘books’][‘author’];


print(jsonData.toString());
Ans= ‘Yashavant Kanetkar’

var data = { "books":[{"name":"Let Us C",var"author":"Yashavant Kanetkar"},


jsonData = data[‘books’][0][‘name’] ; ]};
How to access book name?
print(jsonData.toString());
Ans= ‘Let Us C’

var data = [ {"books": {"name":"Let Us C",var"author":"Yashavant


var1 = data[0]['books']!['author'];
Kanetkar"}, } ];
How to access book author?
[
JSON Code for Examples
{ {
"id": 1, "id": 2,
"name": "Leanne Graham", "name": "Ervin Howell",
"username": "Bret", "username": "Antonette",
"email": "[email protected]", "email": "[email protected]",
"address": { "address": {
"street": "Kulas Light", "street": "Victor Plains",
"suite": "Apt. 556", "suite": "Suite 879",
"city": "Gwenborough", "city": "Wisokyburgh",
"zipcode": "92998-3874", "zipcode": "90566-7771",
"geo": { "geo": {
"lat": "-37.3159", "lat": "-43.9509",
"lng": "81.1496" "lng": "-34.4618"
} }
}, },
"phone": "1-770-736-8031 x56442", "phone": "010-692-6593 x09125",
"website": "hildegard.org", "website": "anastasia.net",
"company": { "company": {
"name": "Romaguera-Crona", "name": "Deckow-Crist",
"catchPhrase": "Multi-layered client-server", "catchPhrase": "Proactive didactic contingency",
"bs": "harness real-time e-markets" "bs": "synergize scalable supply-chains"
} }
}, } ]
JSONPath Expression
JSONPath is a query language for JSON, to get, a portion of values from
JSON response bodies using a simple and familiar syntax.
JSONPath Description
$ Represents the root object.
@ Represents the current object.
. or [] This is the child operator.
.. Recursive descendant.
* Represent a wildcard to obtain all objects.

[] Used to iterate through elements.


[,] Union operator.
[start:end:step] Slice array operator inherited from ES4.
?() Filter operator.
() IT Industry-AcademiaScript expression.
Bridge Program
Examples
Json_path package is required to use json expression

To access a field in the root $.firstName {


"firstName": "John",
[ "John"]
"lastName": "doe",
"age": 26,
To access a field from nested object $.address.city "address": {
[ "Nara" ] "streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
To access fields from nested array $.phoneNumbers[*].number },
[ "phoneNumbers": [
"0123-4567-8888", {
"type": "iPhone",
"0123-4567-8910" "number": "0123-4567-8888"
] },
{
"type": "home",
$.phoneNumbers[?(@.type == "home")].number
"number": "0123-4567-8910"
[ }
"0123-4567-8910" ]
IT Industry-Academia Bridge Program
] }
Example: (json file as application
resource)
Step-1: Create a folder “assets” under root directory and save a .json file with json data.
Step-2: In pubspec.yaml, under assets:
- assets/myjson.json
Step-3: Import the pakcage
import 'package:flutter/services.dart' show rootBundle;
The rootBundle is a top-level property in the services library that provides easy access to the main
asset bundle for an application.
Step-4: Write the following Code to extract information from json file
String str = await rootBundle.loadString('assets/userjdata.json');
var jsonFile = jsonDecode(str);
print(jsonFile[0]['address']['street']);

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.

IT Industry-Academia Bridge Program


API

IT Industry-Academia Bridge Program


Flutter API
Fetching data from the internet is necessary for most apps. Dart and
Flutter provides http package to use http resources.
This package contains a set of high-level functions and classes that
make it easy to consume HTTP resources.
The http package uses await and async features and provides many
high-level methods such as read, get, post, put, head, and delete
methods for sending and receiving data from remote locations.
The http package also provides a standard http client class that
supports the persistent connection. This class is useful when a lot of
requests to be made on a particular server. It should be closed properly
using the close() method.
IT Industry-Academia Bridge Program
API Operations
• The core methods of the http package are as follows:
• Read: This method is used to read or retrieve the representation of
resources.
• Get: This method requests the specified url from the get method and
returns a response as Future<response>. (An Get cannot modify data, its consider a safe method )
• Post: This method is used to submit the data to the specified resources.
• Put: This method is utilized for update capabilities (resource).
• Head: It is similar to the Get method, but without the response body.
• Patch: It is used to update a part of resource.
• Delete: This method is used to remove all the specified resources.
IT Industry-Academia Bridge Program
API

API recipe uses the following steps:


• Add the http package.
• Make a network request using the http package.
• Convert the response into a custom Dart object.
• Fetch and display the data with Flutter.

IT Industry-Academia Bridge Program


Add the http package
To install the http package, add it to the dependencies section of
the pubspec.yaml file. You can find the latest version of the http
package the pub.dev. This is an official Flutter plugin published by
dart.dev and it has a 100% health score
dependencies:
http: ^0.13.4
Import the http package.
import 'package:http/http.dart' as http;
Additionally, in your AndroidManifest.xml file, add the Internet permission.
<uses-permission android:name="android.permission.INTERNET" />
(if there is connection error, please restart emulator or app)
Using hMake a network request
import 'package:http/http.dart' as http;
Future<http.Response> fetchData() async {
return await
http.get(Uri.parse('https://jsonplaceholder.typicode.com'+'/users’));
}

Future is a core Dart class for working with async operations.


The http.get() method returns a Future that contains a Response.
The http.Response class contains the data received from a successful http call.

IT Industry-Academia Bridge Program


Getting the response code and body
Future<Post> fetchData() async {
final response = await http.get( 'https://jsonplaceholder.typicode.com'+'/users’);

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');
}
}

IT Industry-Academia Bridge Program


Example void fetchData() async {
String baseUrl = 'https://jsonplaceholder.typicode.com';
String usersEndpoint = '/users';
Uri uri = Uri.parse('https://jsonplaceholder.typicode.com'+'/users');

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

HTTP response codes


• Informational responses (100–199)
• Successful responses (200–299)
• Redirection messages (300–399)
• Client error responses (400–499)
• Server error responses (500–599)
IT Industry-Academia Bridge Program
Fetch the data with Flutter.
You can call the fetch method in the initState()

class _MyAppState extends State<MyApp> {


Future<Post> post;
@override
void initState() {
super.initState();
post = fetchPost();
}

IT Industry-Academia Bridge Program


Display Data with FutureBuilder
Finally, display the data. You can display the data by using the FutureBuilder widget.
This widget can work easily with async data sources.
FutureBuilder<Post>(
future: post,
builder: (context, abc) {
if (abc.hasData) {
return Text(abc.data.title);
} else if (abc.hasError) {
return Text("${abc.error}");
}
return CircularProgressIndicator(); // By default, it show a loading spinner.
}, );

IT Industry-Academia Bridge Program


Dart Server
import 'dart:io';
Future<void> main() async {
final server = await createServer();
print('Server started: ${server.address} port ${server.port}');
await handleRequests(server);
}
Future<void> handleRequests(HttpServer server) async {
await for (HttpRequest request in server) {
request.response.write('Hello from a Dart server');
await request.response.close();
}}
Future<HttpServer> createServer() async {
final address = InternetAddress.loopbackIPv4;
const port = 4040;
return await HttpServer.bind(address, port);
}
Step-1:
Create a dart project
#bin> dart create –t console-full dartapiserver
#bin/dartapiserver/bin> dart run myserver.dart
Write the web server code in myserver.dart same as written in previous slide before run.
Step-2
#bin/dartapiserver> dart pub add shelf_router
This will add shelf_router dependency in pubspec.yaml file of dartapiserver.
dependencies:
shelf_router: ^1.1.3
API EndPoints
An API endpoint is a point at which an API -- the code that allows two
software programs to communicate with each other.
In other words, API endpoints are the specific digital location where requests
for information are sent by one program to retrieve the digital resource that
exists there. Endpoints specify where APIs can access resources
APIs work by sending requests for information from a web application or
web server and receiving a response.
GET /students
GET /students/prefercne
GET /students/result
IT Industry-Academia Bridge Program
API Handlers
Handlers are responsible for coordinating the client request. Handlers intercept calls, run
required actions, and convert responses to a form consumable by the client by using standard
HTTP protocol elements.
A Handler is any function that handles a Request and returns a Response. It can either handle
the request itself–for example, a static file server that looks up the requested URI on the
filesystem–or it can do some processing and forward it to another handler–for example, a
logger that prints information about requests and responses to the command line. The latter
kind of handler is called "middleware",

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';

void main() async {


final Map<String, dynamic> map = json.decode(File('users.json').readAsStringSync());
final List<dynamic> data = map['users'];
final app = Router();
app.get('/', (Request request) {
return Response.ok('Hello World'); #dart run dartapiserver
});
app.get('/users', (Request request) { Browser
return Response.ok(json.encode(data)); http://localhost:4040/users
});
await io.serve(app, 'localhost', 4040);
}
Source
https://www.youtube.com/watch?v=v7FhaV9e3yY
https://
stackoverflow.com/questions/55430061/unhandled-exception-internallinkedhashmapstring-dynamic-is-not-a-su
btype-of
https://pub.dev/documentation/shelf_router/latest/shelf_router/Router-class.html
https://pub.dev/documentation/shelf_router/latest/
https://medium.com/@ben75930/dart-server-with-good-practices-f18ed33868e5
https://dev.to/infiniteoverflow/build-apis-for-various-http-methods-in-dart-n87
https://www.etiennetheodore.com/simple-dart-rest-api/
https://dart.dev/tutorials/server/httpserver
https://github.com/Dev-Owl/dart_backend_example/blob/main/bin/serveTestData.dart
https://levelup.gitconnected.com/dart-backend-by-example-rest-api-a8a1004dc705
https://dev.to/infiniteoverflow/create-an-api-with-dart-heroku-477k
https://github.com/dart-lang/samples/tree/master/server/simple
https://www.kodeco.com/31602619-building-dart-apis-with-google-cloud-run
IT Industry-Academia Bridge Program
What protocol does REST follow?
• A) FTP
• B) HTTP
• C) SFTP
• D) FTPS

IT Industry-Academia Bridge Program


What does HTTP Code 200 represent in REST?
• A) Success
• B) Completed
• C) Failure
• D) Error

IT Industry-Academia Bridge Program


In Flutter, which package is commonly used for making HTTP requests
to a REST API?
• A) http
• B) http_package
• C) rest_flutter
• D) flutter_http

IT Industry-Academia Bridge Program


What is the primary function of REST API in mobile app development
with Flutter?
• A) Rendering UI components
• B) Managing local state
• C) Handling user authentication
• D) Communicating with a server

IT Industry-Academia Bridge Program


Which HTTP method is typically used to retrieve data from a REST API
in Flutter?
• A) GET
• B) POST
• C) PUT
• D) DELETE

IT Industry-Academia Bridge Program


What is the purpose of an API key in REST API authentication for
Flutter apps?
• A) Encrypting data
• B) Authorizing access
• C) Rendering UI
• D) Managing local storage

IT Industry-Academia Bridge Program


• Which Flutter widget is commonly used for displaying data fetched
from a REST API?
• A) Text
• B) ListView
• C) Container
• D) AppBar

IT Industry-Academia Bridge Program


What does JSON stand for?
• A) JavaScript Object Notation
• B) Java Syntax Object Notation
• C) JSON Object Naming
• D) JavaScript Oriented Notation

IT Industry-Academia Bridge Program


Which data types are natively supported in JSON?
• A) int, float, boolean, string, null
• B) number, bool, char, text, void
• C) integer, boolean, string, void
• D) numeric, bool, string, none

IT Industry-Academia Bridge Program


• In JSON, how can you represent an array of objects?
• A) { "key": [ {...}, {...}, {...} ] }
• B) [ {...}, {...}, {...} ]
• C) ( {...}, {...}, {...} )
• D) < {...}, {...}, {...} >

IT Industry-Academia Bridge Program


Which character is used to separate different key-value pairs in a JSON
object?
• A) :
• B) ;
• C) ,
• D) .

IT Industry-Academia Bridge Program


Serverless
Google provides serverless APIs environment on
Cloud Run
Cloud Function
There are three major types of Cloud Functions:
• HTTPS functions: These can be triggered through an HTTP request;
supported HTTP methods include GET, POST, PUT, DELETE, and OPTIONS
• Callable functions: These functions can be triggered by explicitly calling
them from an app
• Background functions: Triggered based on events generated by Firebase
services like Authentication, Firestore, Realtime Database, and Storage
IT Industry-Academia Bridge Program

You might also like