SlideShare une entreprise Scribd logo
1  sur  43
API-Application
Programming
Interface
TK2323 Mobile Programming
Sem 1 2017/2018
Lam Meng Chun
lammc@ukm.edu.my (G-02)
Outline
JSON
▹ Number
▹ String
▹ Boolean
▹ Object
▹ Array
API
▹ Concept
JSON in Android
2
JSON
3
4 JSON
▹JSON (JavaScript Object Notation) is a lightweight data-
interchange format.
▸Data is in name/value pairs
▸Data is separated by commas ,
▸Curly braces hold objects { }
▸Square brackets hold arrays [ ]
4
5 JSON
▹ http://lrgs.ftsm.ukm.my/phpmyadmin/index.php
▹ http://lrgs.ftsm.ukm.my/phpmyadmin/ftp
5
6 Name/Value pairs
Name/Key Value:
{ “Matrix No” : “A111111” }
7 JSON
▹JSON values can be:
7
Type Example
Number 12 , 12.5
String “Alan”
Boolean True, False
Array “Car_Brands” : [ “Honda”, “Mercedes” , “Subaru” ]
Object “User”: {“Matrix_No”: ”A111111”,
“Name”: ”Alan”}
8 Name/Value pairs
Name Value:
{ “Matrix No” : “A111111” }
{ “Fees” : 500.00}
String Matrix No = “A111111”;
float Fees = 500.00;
9 JSON
▹A number (integer or
floating point)
▹A string (in double
quotes)
▹A Boolean (true or
false)
9
{
“Burger Price“ : 20.0
}
{
“Burger Name“ : “TK2323 Burger”
}
{
“Delicious“ : false
}
10 JSON
▹An array (in square brackets) ▹An object (in curly braces)
10
{
“Courses” : [ “TK2323”, “TR2312”,
“TP4345”]
}
“Member”: {
"name":“Ali",
"age":30,
“Matrix No":”A111111”
}
{
“Prices” : [ 10, 20, 15 ,88]
}
11 JSON: Nested
▹List of objects inside an array
▹A “books” object contains array of “language”, “edition”
and “lastName” object
11
12 JSON
API
13
14
API - Concept
Select Club_ID, Club_name
From Clubs (Web)
Select Club_ID, Club_name
From Clubs (Android)…
14
Clubs
Club_ID Club_Name
ClubSIG01 Robotic (ARViS)
ClubSIG02 Interactive Multimedia (iMec)
ClubSIG03 Mobile Apps Development (MAD
Club)
15
API - Concept
Select Club_ID, Club_name
From Clubs (API)
15
Clubs
Club_ID Club_Name
ClubSIG01 Robotic (ARViS)
ClubSIG02 Interactive Multimedia (iMec)
ClubSIG03 Mobile Apps Development (MAD
Club)
16
API –
Concept
Request and
Response
▹http://samples.openw
eathermap.org/data/2.5
/forecast?q=M%C3%BC
nchen,DE&appid=b1b15
e88fa797225412429c1c5
0c122a1
▹www.google.com
17 API - Concept
Endpoint
▹ Basically is an URL
▹ Description
Method
▹ POST (Create)
▹ GET (Read)
▹ PUT
(Update/Relace)
▹ DELETE (Delete)
PARAMETER
▹ Key
▹ Data Type
▹ Section
(In URL/ in Body)
▹ Required or not
▹http://petstore.swagger.io/
▹http://petstore.swagger.io/v2/store/inventory
18 Example
19
20 Postman - Example
▹How to make request
▸End Point
▸Method
▸Data
21
Postman –
End Point
and Method
22
Postman –
Data in URL
23
Postman –
Data in Body
24
API – Method and status
code
HTTP Verb CRUD
Entire Collection (e.g.
/customers)
Specific Item (e.g.
/customers/{id})
POST Create 201 (Created), 'Location' header
with link to /customers/{id}
containing new ID.
404 (Not Found), 409
(Conflict) if resource already
exists..
GET Read 200 (OK), list of customers. Use
pagination, sorting and filtering to
navigate big lists.
200 (OK), single customer.
404 (Not Found), if ID not
found or invalid.
PUT Update/Replace 405 (Method Not Allowed), unless
you want to update/replace every
resource in the entire collection.
200 (OK) or 204 (No
Content). 404 (Not Found), if
ID not found or invalid.
DELETE Delete 405 (Method Not Allowed), unless
you want to delete the whole
collection—not often desirable.
200 (OK). 404 (Not Found), if
ID not found or invalid.
25 API – Server side
▹TTTP2543 Web Programming
▹Possible server side technology (microframework)
▸PhP (Lumen, Wave Framework, Slim…)
▸Python (Flask, FALCON,…)
▸Ruby on Rails
26 Resources
▹http://petstore.swagger.io/
▹https://jsonlint.com
▹https://jsonformatter.curiousconcept.com/
▹https://www.getpostman.com/
▹HTTP response status codes: https://developer.mozilla.org/en-
US/docs/Web/HTTP/Status
Request from
Android
27
28
Request from Android -
Libraries
▹OkHttp
▹Retrofit
▹Volley
29 Volley
30 Volley - Request
▹4 Parameters needed
▸Method (GET, PUT, POST, DELETE)
▸URL
▸Response Listener
▸Error Listerner
▹Data to be sent
Request from
Android – No data
sent
31
32 Volley - Request
public static final String JSON_VIEW_MEMBER_URL = "http://lrgs.ftsm.ukm.my/users/lam/view_member.php";
StringRequest myReq = new StringRequest(
Request.Method.GET,
JSON_VIEW_MEMBER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
},
new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
33
Volley –
Request (No
data)
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonArray = jsonResponse.getJSONArray("result");
Member member;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
String matrix = jo.getString("fld_matrix_no");
String name = jo.getString("fld_member_name");
String club = jo.getString("fld_club_id");
String status = jo.getString("fld_status");
member = new Member(id, matrix, name, club, status);
member_list.add(matrix + ", " + name + ", " + club + ", " + status);
member_list_object.add(member);
}
memberAdapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, member_list);
lv_member.setAdapter(memberAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
34
Volley -
Request
new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(myReq);
35
36
▹JSONArray
▸A dense indexed sequence of
values.
▹JSONObject
▹A modifiable set of
name/value mappings.
Request from
Android – Data in
Body
37
38
Volley – Request (Data in
body)
public static final String JSON_ADD_MEMBER_URL = "http://lrgs.ftsm.ukm.my/users/lam/add_member.php";
StringRequest myReq = new StringRequest(Request.Method.POST, JSON_ADD_MEMBER_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", response);
adapter.clear();
populateMemberRequest();
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("matrix", id);
params.put("name", name);
params.put("club_id", club_id);
params.put("status", status);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(myReq);
}
39
Volley – Request (Data in
body)
public static final String JSON_ADD_MEMBER_URL =
"http://lrgs.ftsm.ukm.my/users/lam/add_member.php";
StringRequest myReq = new StringRequest(Request.Method.POST, JSON_ADD_MEMBER_URL, new
Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", response);
adapter.clear();
populateMemberRequest();
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
})
{
Data is here
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(myReq);
}
40
Volley – Request (Data in
body)
public static final String JSON_ADD_MEMBER_URL =
"http://lrgs.ftsm.ukm.my/users/lam/add_member.php";
StringRequest myReq = new StringRequest(Request.Method.POST, JSON_ADD_MEMBER_URL, new
Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new ErrorListener() {
})
{
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("matrix", id);
params.put("name", name);
params.put("club_id", club_id);
params.put("status", status);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(myReq);
Request from
Android – Data in
URL
41
42
Volley – Request (Data in
URL)
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) { } else { }
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DeleteMemberRequest deleteMemberRequest = new DeleteMemberRequest(matrix_no,
responseListener);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(deleteMemberRequest);
}
}
43
Volley – Request (Data in
URL)
public class DeleteMemberRequest extends StringRequest {
/* private Map<String, String> params; */
public DeleteMemberRequest(String matrix_no, Response.Listener<String> listener)
{
super(Method.DELETE, JSON_DELETE_MEMBER_URL + matrix_no, listener, null);
/* params = new HashMap<>();
params.put("matrix_no", matrix_no);*/
}

Contenu connexe

Tendances

Domain Specific Languages (EclipseCon 2012)
Domain Specific Languages (EclipseCon 2012)Domain Specific Languages (EclipseCon 2012)
Domain Specific Languages (EclipseCon 2012)Sven Efftinge
 
Introduction to Event Sourcing and CQRS (IASA-IL)
Introduction to Event Sourcing and CQRS (IASA-IL)Introduction to Event Sourcing and CQRS (IASA-IL)
Introduction to Event Sourcing and CQRS (IASA-IL)Vladik Khononov
 
Indexing and Performance Tuning
Indexing and Performance TuningIndexing and Performance Tuning
Indexing and Performance TuningMongoDB
 
Oracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseOracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseMarco Gralike
 
Zhongl scala summary
Zhongl scala summaryZhongl scala summary
Zhongl scala summarylunfu zhong
 
Devoxx 2012 hibernate envers
Devoxx 2012   hibernate enversDevoxx 2012   hibernate envers
Devoxx 2012 hibernate enversRomain Linsolas
 
Security Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Security Slicing for Auditing XML, XPath, and SQL Injection VulnerabilitiesSecurity Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Security Slicing for Auditing XML, XPath, and SQL Injection VulnerabilitiesLionel Briand
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scalab0ris_1
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Ramamohan Chokkam
 
Codereview Topics
Codereview TopicsCodereview Topics
Codereview TopicsMax Kleiner
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesKaniska Mandal
 
MongoDB - How to model and extract your data
MongoDB - How to model and extract your dataMongoDB - How to model and extract your data
MongoDB - How to model and extract your dataFrancesco Lo Franco
 
Make Your SW Component Testable
Make Your SW Component TestableMake Your SW Component Testable
Make Your SW Component TestableLi-Wei Cheng
 

Tendances (18)

Domain Specific Languages (EclipseCon 2012)
Domain Specific Languages (EclipseCon 2012)Domain Specific Languages (EclipseCon 2012)
Domain Specific Languages (EclipseCon 2012)
 
Introduction to Event Sourcing and CQRS (IASA-IL)
Introduction to Event Sourcing and CQRS (IASA-IL)Introduction to Event Sourcing and CQRS (IASA-IL)
Introduction to Event Sourcing and CQRS (IASA-IL)
 
CAVE Overview
CAVE OverviewCAVE Overview
CAVE Overview
 
RIA and Ajax
RIA and AjaxRIA and Ajax
RIA and Ajax
 
Indexing and Performance Tuning
Indexing and Performance TuningIndexing and Performance Tuning
Indexing and Performance Tuning
 
AJAX
AJAXAJAX
AJAX
 
Oracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory DatabaseOracle Database - JSON and the In-Memory Database
Oracle Database - JSON and the In-Memory Database
 
Zhongl scala summary
Zhongl scala summaryZhongl scala summary
Zhongl scala summary
 
Devoxx 2012 hibernate envers
Devoxx 2012   hibernate enversDevoxx 2012   hibernate envers
Devoxx 2012 hibernate envers
 
Clean code
Clean codeClean code
Clean code
 
Security Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Security Slicing for Auditing XML, XPath, and SQL Injection VulnerabilitiesSecurity Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Security Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scala
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
 
Codereview Topics
Codereview TopicsCodereview Topics
Codereview Topics
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml Classes
 
MongoDB - How to model and extract your data
MongoDB - How to model and extract your dataMongoDB - How to model and extract your data
MongoDB - How to model and extract your data
 
Make Your SW Component Testable
Make Your SW Component TestableMake Your SW Component Testable
Make Your SW Component Testable
 

Similaire à Tk2323 lecture 9 api json

RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기Juwon Kim
 
Wcf data services
Wcf data servicesWcf data services
Wcf data servicesEyal Vardi
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.Nerd Tzanetopoulos
 
Применение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взглядПрименение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взглядCOMAQA.BY
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceMaarten Balliauw
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed versionBruce McPherson
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoHasnain Iqbal
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Oliver Gierke
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Integrating Force.com with Heroku
Integrating Force.com with HerokuIntegrating Force.com with Heroku
Integrating Force.com with HerokuPat Patterson
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedMarcinStachniuk
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIEyal Vardi
 
UI5Con presentation on UI5 OData V4 Model
UI5Con presentation on UI5 OData V4 ModelUI5Con presentation on UI5 OData V4 Model
UI5Con presentation on UI5 OData V4 ModelPatric Ksinsik
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 

Similaire à Tk2323 lecture 9 api json (20)

RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
Применение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взглядПрименение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взгляд
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Integrating Force.com with Heroku
Integrating Force.com with HerokuIntegrating Force.com with Heroku
Integrating Force.com with Heroku
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
 
UI5Con presentation on UI5 OData V4 Model
UI5Con presentation on UI5 OData V4 ModelUI5Con presentation on UI5 OData V4 Model
UI5Con presentation on UI5 OData V4 Model
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 

Plus de MengChun Lam

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensorMengChun Lam
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and threadMengChun Lam
 
Tk2323 lecture 8 firebase
Tk2323 lecture 8   firebaseTk2323 lecture 8   firebase
Tk2323 lecture 8 firebaseMengChun Lam
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui uxMengChun Lam
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)MengChun Lam
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storageMengChun Lam
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler viewMengChun Lam
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql MengChun Lam
 
Tk2323 lecture 3 intent
Tk2323 lecture 3   intentTk2323 lecture 3   intent
Tk2323 lecture 3 intentMengChun Lam
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 uiMengChun Lam
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile applicationMengChun Lam
 

Plus de MengChun Lam (11)

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensor
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and thread
 
Tk2323 lecture 8 firebase
Tk2323 lecture 8   firebaseTk2323 lecture 8   firebase
Tk2323 lecture 8 firebase
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui ux
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler view
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
Tk2323 lecture 3 intent
Tk2323 lecture 3   intentTk2323 lecture 3   intent
Tk2323 lecture 3 intent
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 ui
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile application
 

Tk2323 lecture 9 api json

  • 1. API-Application Programming Interface TK2323 Mobile Programming Sem 1 2017/2018 Lam Meng Chun lammc@ukm.edu.my (G-02)
  • 2. Outline JSON ▹ Number ▹ String ▹ Boolean ▹ Object ▹ Array API ▹ Concept JSON in Android 2
  • 4. 4 JSON ▹JSON (JavaScript Object Notation) is a lightweight data- interchange format. ▸Data is in name/value pairs ▸Data is separated by commas , ▸Curly braces hold objects { } ▸Square brackets hold arrays [ ] 4
  • 5. 5 JSON ▹ http://lrgs.ftsm.ukm.my/phpmyadmin/index.php ▹ http://lrgs.ftsm.ukm.my/phpmyadmin/ftp 5
  • 6. 6 Name/Value pairs Name/Key Value: { “Matrix No” : “A111111” }
  • 7. 7 JSON ▹JSON values can be: 7 Type Example Number 12 , 12.5 String “Alan” Boolean True, False Array “Car_Brands” : [ “Honda”, “Mercedes” , “Subaru” ] Object “User”: {“Matrix_No”: ”A111111”, “Name”: ”Alan”}
  • 8. 8 Name/Value pairs Name Value: { “Matrix No” : “A111111” } { “Fees” : 500.00} String Matrix No = “A111111”; float Fees = 500.00;
  • 9. 9 JSON ▹A number (integer or floating point) ▹A string (in double quotes) ▹A Boolean (true or false) 9 { “Burger Price“ : 20.0 } { “Burger Name“ : “TK2323 Burger” } { “Delicious“ : false }
  • 10. 10 JSON ▹An array (in square brackets) ▹An object (in curly braces) 10 { “Courses” : [ “TK2323”, “TR2312”, “TP4345”] } “Member”: { "name":“Ali", "age":30, “Matrix No":”A111111” } { “Prices” : [ 10, 20, 15 ,88] }
  • 11. 11 JSON: Nested ▹List of objects inside an array ▹A “books” object contains array of “language”, “edition” and “lastName” object 11
  • 14. 14 API - Concept Select Club_ID, Club_name From Clubs (Web) Select Club_ID, Club_name From Clubs (Android)… 14 Clubs Club_ID Club_Name ClubSIG01 Robotic (ARViS) ClubSIG02 Interactive Multimedia (iMec) ClubSIG03 Mobile Apps Development (MAD Club)
  • 15. 15 API - Concept Select Club_ID, Club_name From Clubs (API) 15 Clubs Club_ID Club_Name ClubSIG01 Robotic (ARViS) ClubSIG02 Interactive Multimedia (iMec) ClubSIG03 Mobile Apps Development (MAD Club)
  • 17. 17 API - Concept Endpoint ▹ Basically is an URL ▹ Description Method ▹ POST (Create) ▹ GET (Read) ▹ PUT (Update/Relace) ▹ DELETE (Delete) PARAMETER ▹ Key ▹ Data Type ▹ Section (In URL/ in Body) ▹ Required or not ▹http://petstore.swagger.io/ ▹http://petstore.swagger.io/v2/store/inventory
  • 19. 19
  • 20. 20 Postman - Example ▹How to make request ▸End Point ▸Method ▸Data
  • 24. 24 API – Method and status code HTTP Verb CRUD Entire Collection (e.g. /customers) Specific Item (e.g. /customers/{id}) POST Create 201 (Created), 'Location' header with link to /customers/{id} containing new ID. 404 (Not Found), 409 (Conflict) if resource already exists.. GET Read 200 (OK), list of customers. Use pagination, sorting and filtering to navigate big lists. 200 (OK), single customer. 404 (Not Found), if ID not found or invalid. PUT Update/Replace 405 (Method Not Allowed), unless you want to update/replace every resource in the entire collection. 200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid. DELETE Delete 405 (Method Not Allowed), unless you want to delete the whole collection—not often desirable. 200 (OK). 404 (Not Found), if ID not found or invalid.
  • 25. 25 API – Server side ▹TTTP2543 Web Programming ▹Possible server side technology (microframework) ▸PhP (Lumen, Wave Framework, Slim…) ▸Python (Flask, FALCON,…) ▸Ruby on Rails
  • 28. 28 Request from Android - Libraries ▹OkHttp ▹Retrofit ▹Volley
  • 30. 30 Volley - Request ▹4 Parameters needed ▸Method (GET, PUT, POST, DELETE) ▸URL ▸Response Listener ▸Error Listerner ▹Data to be sent
  • 31. Request from Android – No data sent 31
  • 32. 32 Volley - Request public static final String JSON_VIEW_MEMBER_URL = "http://lrgs.ftsm.ukm.my/users/lam/view_member.php"; StringRequest myReq = new StringRequest( Request.Method.GET, JSON_VIEW_MEMBER_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } });
  • 33. 33 Volley – Request (No data) public void onResponse(String response) { try { JSONObject jsonResponse = new JSONObject(response); JSONArray jsonArray = jsonResponse.getJSONArray("result"); Member member; for (int i = 0; i < jsonArray.length(); i++) { JSONObject jo = jsonArray.getJSONObject(i); String matrix = jo.getString("fld_matrix_no"); String name = jo.getString("fld_member_name"); String club = jo.getString("fld_club_id"); String status = jo.getString("fld_status"); member = new Member(id, matrix, name, club, status); member_list.add(matrix + ", " + name + ", " + club + ", " + status); member_list_object.add(member); } memberAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, member_list); lv_member.setAdapter(memberAdapter); } catch (JSONException e) { e.printStackTrace(); } }
  • 34. 34 Volley - Request new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); RequestQueue queue = Volley.newRequestQueue(this); queue.add(myReq);
  • 35. 35
  • 36. 36 ▹JSONArray ▸A dense indexed sequence of values. ▹JSONObject ▹A modifiable set of name/value mappings.
  • 37. Request from Android – Data in Body 37
  • 38. 38 Volley – Request (Data in body) public static final String JSON_ADD_MEMBER_URL = "http://lrgs.ftsm.ukm.my/users/lam/add_member.php"; StringRequest myReq = new StringRequest(Request.Method.POST, JSON_ADD_MEMBER_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("Response", response); adapter.clear(); populateMemberRequest(); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("Error.Response", error.toString()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("matrix", id); params.put("name", name); params.put("club_id", club_id); params.put("status", status); return params; } }; RequestQueue queue = Volley.newRequestQueue(this); queue.add(myReq); }
  • 39. 39 Volley – Request (Data in body) public static final String JSON_ADD_MEMBER_URL = "http://lrgs.ftsm.ukm.my/users/lam/add_member.php"; StringRequest myReq = new StringRequest(Request.Method.POST, JSON_ADD_MEMBER_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("Response", response); adapter.clear(); populateMemberRequest(); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("Error.Response", error.toString()); } }) { Data is here }; RequestQueue queue = Volley.newRequestQueue(this); queue.add(myReq); }
  • 40. 40 Volley – Request (Data in body) public static final String JSON_ADD_MEMBER_URL = "http://lrgs.ftsm.ukm.my/users/lam/add_member.php"; StringRequest myReq = new StringRequest(Request.Method.POST, JSON_ADD_MEMBER_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { } }, new ErrorListener() { }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("matrix", id); params.put("name", name); params.put("club_id", club_id); params.put("status", status); return params; } }; RequestQueue queue = Volley.newRequestQueue(this); queue.add(myReq);
  • 41. Request from Android – Data in URL 41
  • 42. 42 Volley – Request (Data in URL) Response.Listener<String> responseListener = new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonResponse = new JSONObject(response); boolean success = jsonResponse.getBoolean("success"); if (success) { } else { } } catch (JSONException e) { e.printStackTrace(); } } }; DeleteMemberRequest deleteMemberRequest = new DeleteMemberRequest(matrix_no, responseListener); RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); queue.add(deleteMemberRequest); } }
  • 43. 43 Volley – Request (Data in URL) public class DeleteMemberRequest extends StringRequest { /* private Map<String, String> params; */ public DeleteMemberRequest(String matrix_no, Response.Listener<String> listener) { super(Method.DELETE, JSON_DELETE_MEMBER_URL + matrix_no, listener, null); /* params = new HashMap<>(); params.put("matrix_no", matrix_no);*/ }