0% found this document useful (0 votes)
7 views34 pages

Part 3 Rest-Api

Uploaded by

Bóng Hồng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views34 pages

Part 3 Rest-Api

Uploaded by

Bóng Hồng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Khoa CNTT DH Nong Lam

Agenda
• Gestures REST- API- JSON

2/11/2012 Android Insights - 3 1/18


Course Topics Khoa CNTT DH Nong Lam

Introduction to Intership Mobile Programming


Part 1: Reviews Layout, Fragment
Part 2: Reviews Async Task, Sqlite Database, Connect PHP
Server JSON Parser.
Part 3: Webservices SOAP, REST Structure
Part 4: Connect Webservices, Parse Json, XML.
Part 5: QRCode Scanner, Barcode Scanner
Part 6,7,8: Flutter Structure, Call API,…

Khoa CNTT ĐH Nông Lâm - Võ Tấn 2


Khoa CNTT DH Nong Lam

What is REST?
• What is RESTful API?
• RESTful API is a standard used in designing API for
web applications (designing Web services) to support
the management of resources. It focuses on system
resources (text files, images, audio, video, or dynamic
data ...), including resource states that are formatted
and transmitted over HTTP.
Khoa CNTT DH Nong Lam

What is REST?
• REST stands for Representational State Transfer. (It is
sometimes spelled "ReST".)
• REST is an architecture style for designing networked
applications,
• REST uses HTTP for all four CRUD
(Create/Read/Update/Delete) operations.
Khoa CNTT DH Nong Lam

What is REST?
Khoa CNTT DH Nong Lam
How does RESTful work?
Khoa CNTT DH Nong Lam

Concept of JSON Format:

• JSON (JavaScript Object Notation) is defined according to the


JavaScript language, ECMA-262 standard of 1999, structure is a
simple text format with nested data fields. JSON is used to
exchange data between components of a system compatible with
most languages C, C ++, C #, Java, JavaScript, Perl, Python ...
• JSON is built on two main structures:
• The set of name / value pairs, in many different languages, can be
object, record, struct, dictionary, hash table, keyed list ...
• A set of lists of values, be it an array, vector, list or sequence.
Khoa CNTT DH Nong Lam

JSON Example

{
"id": "100005823642721",
"first_name": “IT_NongLam",
"gender": "male",
"last_name": “IT",
"link": "https://www.facebook.com/itnonglam",
"locale": "en_US",
"birthday": "December 20, 1980",
"name": “Nong Lam IT",
"username": “vttoanit"
}
Khoa CNTT DH Nong Lam

JSON Array Example


• {
• "Sanphams":
• [
• {"MaSP": "sp_1xxx", "TenSP": "DELL Inspiron 14NR", "SoLuong": 100,
• "DonGia": 150000, "ThanhTien": 0,
• "Pictures": "https://fit.hcmuaf.edu.vn/h1.png"
• },
• {"MaSP": "sp_2yyyy", "TenSP": "HP Inspiron 113", "SoLuong": 130,
• "DonGia": 140000, "ThanhTien": 0,
• "Pictures": "https://fit.hcmuaf.edu.vn/h2.png"
• }
• ],
• "MaDM": "DM1",
• "TenDM": "Computer goods"
• }
Khoa CNTT DH Nong Lam

JSON Parsing
Reading and writing JSON format is built into Android SDK (it is in
the org.json library)

JSONObject: an object that manages JSON in the form of an


Object.
JSONArray: JSON management object in the form of a set of
Objects or Array.
JSONStringer: an object that converts JSON data into a string.
JSONTokener: converts the JSON object (standard RFC-4627)
encoding the string one to the corresponding object.
Khoa CNTT DH Nong Lam

Spring boot – Rest Api


Using Spring Boot to create a Restful API will use Spring Boot,
JPA and MySQL to create an API that supports 4 basic features:
add (C), view (R), update (U) and delete (D).
RESTFul API that we created for the purpose of viewing, adding,
deleting and editing employee information. Information for each
employee includes first name (firstName), first name (lastName)
and email address.
Khoa CNTT DH Nong Lam

Rest- Api
Method Api link Descriptions
GET /api/v1/employees Show all employees
Displays employees
GET /api/v1/employees/1
whose id is 1
POST /api/v1/employees Add Employees
Update employees
PUT /api/v1/employees/1
whose id is 1
Delete employees whose
DELETE /api/v1/employess/1
id is 1
Khoa CNTT DH Nong Lam
Khoa CNTT DH Nong Lam

Create a Spring Boot Application ☞ https://start.spring.io/


Khoa CNTT DH Nong Lam

Create a Spring Boot Application ☞ https://start.spring.io/


Khoa CNTT DH Nong Lam

Create a Spring Boot Application ☞ https://start.spring.io/


Khoa CNTT DH Nong Lam

Create a Spring Boot Application ☞ https://start.spring.io/


Khoa CNTT DH Nong Lam

Create a Spring Boot Application ☞ https://start.spring.io/


Khoa CNTT DH Nong Lam

Some Important Anotation in Spring boot


@RequestMapping("/api") to declare the urls of the apis in this controller will start with '/api’
@RequestBody corresponds to the body of the request
@Valid to ensure the request body is valid if we use validation annotations like @NotBlank...
@PathVariable mapping path variable to method call parameter variable
@Entity Models will have to use the annotation
@Table(name = "nametable") on the model to change the name of the table you want to
mapping
@ID : define primary key
@NotBlank : cannot be null or empty
@Column(nullable = false) configure column as declared
@GeneratedValue : auto-increment
@Repository This class is responsible for executing query statements to the database.
Khoa CNTT DH Nong Lam

Create a repository with Java Interface and name it EmployeeRepository


Khoa CNTT DH Nong Lam

Employee.java
Khoa CNTT DH Nong Lam

EmployeeController.ja
va
@RestController

@RequestMapping("api/v1")

public class EmployeeController {

@Autowired

private EmployeeRepository employeeRepository;


@GetMapping("employees")

public List<Employee> getAllEmployees() {

return employeeRepository.findAll();

}
Khoa CNTT DH Nong Lam

EmployeeController.ja
va
@GetMapping("employees/{id}")

public ResponseEntity<Employee>
getEmployeeById(@PathVariable(value = "id") Long
employeeId) throws ResourceNotFoundException {

Employee employee =
employeeRepository.findById(employeeId).orElseThrow(() ->
new ResourceNotFoundException("Nhân viên này không tồn
tại: " + employeeId));

return ResponseEntity.ok().body(employee);

}
Khoa CNTT DH Nong Lam

EmployeeController.ja
va
@PostMapping("employees")

public Employee createEmployee(@Valid @RequestBody Employee


employee) {

return employeeRepository.save(employee);

}
Khoa CNTT DH Nong Lam

EmployeeController.ja
va
@PutMapping("employees/{id}")

public ResponseEntity<Employee>
updateEmployee(@PathVariable(value = "id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws
ResourceNotFoundException {

Employee employee = employeeRepository.findById(employeeId)


.orElseThrow(() -> new ResourceNotFoundException("Nhân viên này
không tồn tại: " + employeeId));
employee.setEmail(employeeDetails.getEmail());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());

final Employee updatedEmployee =


employeeRepository.save(employee);

return ResponseEntity.ok(updatedEmployee); }
Khoa CNTT DH Nong Lam

EmployeeController.ja
va
@DeleteMapping(“/employees/{id}")

public Map<String, Boolean> deleteEmployee(@PathVariable(value


= "id") Long employeeId) throws ResourceNotFoundException {

Employee employee = employeeRepository.findById(employeeId)


.orElseThrow(() -> new ResourceNotFoundException("Nhân viên này
không tồn tại: " + employeeId));
employeeRepository.delete(employee);

Map<String, Boolean> response = new HashMap<>();


response.put("deleted", Boolean.TRUE);

return response;

}
Khoa CNTT DH Nong Lam
Run Project Spring
boot
Khoa CNTT DH Nong Lam
Test Rest Api Spring
boot
https://www.postman.com/
Khoa CNTT DH Nong Lam
Test Rest Api Spring
boot
Khoa CNTT DH Nong Lam
Test Rest Api Spring
boot
Khoa CNTT DH Nong Lam
Test Rest Api Spring
boot
Khoa CNTT DH Nong Lam
Test Rest Api Spring
boot
Khoa CNTT DH Nong Lam
Test Rest Api Spring
boot
Khoa CNTT DH Nong Lam

END
34

You might also like