0% found this document useful (0 votes)
12 views

Session01 - APIs & Spring Core

bai 1 smc

Uploaded by

k42.dkhao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Session01 - APIs & Spring Core

bai 1 smc

Uploaded by

k42.dkhao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Session 01: APIs and Spring Core

Objectives
• APIs
• RESTful APIs
• Spring Core
• Maven

R2S Academy - Internal Use 2


Introduction (1)
Example
• Travel Apps: Integrate weather information into travel apps to help users
plan their trips according to weather conditions.
• E-commerce Websites: Weather information can be used on e-commerce
websites to suggest relevant products based on the user's location and
weather (e.g., displaying raincoats when rain is forecasted).

We need an online service that provides global weather


data to integrate real-time and forecast weather
information into their applications, websites

R2S Academy - Internal Use 3


Introduction (2)
Example
• Travel Apps: Integrate weather information into travel apps to help users plan their trips
according to weather conditions.
• E-commerce Websites: Weather information can be used on e-commerce websites to
suggest relevant products based on the user's location and weather (e.g., displaying
raincoats when rain is forecasted).
Online service
that provides global
weather data Travel Apps/E-
commerce Website

API
R2S Academy - Internal Use 4
Introduction (3)
APIs
• API (Application Programming Interface) is a set of rules and protocols used to create and interact
with software or other services.
• An API defines the ways in which different software components can communicate with each other.
• This includes specifying the types of data and actions that can be performed, as well as how to send
and receive messages between applications.
Defines the
Actions
ways

Types of
data

R2S Academy - Internal Use 5


Introduction (4)
APIs - Common Classification
• According to the level of access:
- Public APIs: Provided publicly for everyone to use.
- Private APIs: Reserved for internal use within the organization or application.
• According to the access method:
- RESTful APIs: Utilize the HTTP protocol and adhere to the principles of REST.
- SOAP APIs: Utilize the SOAP (Simple Object Access Protocol) protocol to transmit
data.
• According to the return data format:
- JSON API: APIs return data in JSON (JavaScript Object Notation) format.
- XML API: APIs return data in XML (eXtensible Markup Language) format.
• A new type of API: GraphQL
R2S Academy - Internal Use 6
RESTful APIs (1)
• Utilize the HTTP protocol and adhere to the principles of REST.

- GET — retrieve a specific resource (by id) or a collection of resources


- POST — create a new resource
- PUT — update a specific resource (by id)
- DELETE — remove a specific resource by id

R2S Academy - Internal Use 7


RESTful APIs (2)
• Example

Select - R Insert - C Update - U Delete - D

R2S Academy - Internal Use 8


RESTful APIs (3)
Creating a RESTful API
• Create the Spring Boot Project
• Define Database configurations
• Create an Entity Class
• Create JPA Data Repository layer 6 steps
• Create Rest Controllers and map API requests
• Build, run, and Test

R2S Academy - Internal Use 9


RESTful APIs (4)
Create the Spring Boot Project
• First, go to https://start.spring.io/ and create a project with below settings

◦ Group name: It is also similar to the Package name.


◦ Artifact name: It is the same as Name.
◦ Package name = GroupName.ArtifactName

R2S Academy - Internal Use 10


RESTful APIs (5)
Create the Spring Boot Project
• Dependencies
- Web: Full-stack web development with Tomcat
- DevTools: Spring Boot Development Tools
- JPA: Java Persistence API including spring-data-JPA
- MySQL: MySQL JDBC driver (or SQL Server)

R2S Academy - Internal Use 11


RESTful APIs (6)
Create the Spring Boot Project
• The screenshot below shows a demo project

R2S Academy - Internal Use 12


RESTful APIs (7)
Define Database configurations
• MySQL: Create the database name in database server and define connection
properties application.properties
## Database Properties
spring.datasource.url = jdbc:mysql://localhost:3306/db?useSSL=false
spring.datasource.username = root
spring.datasource.password = root

## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)


spring.jpa.hibernate.ddl-auto = update

R2S Academy - Internal Use 13


RESTful APIs (8)
Define Database configurations
• SQL Server: Create the database name in database server and define
connection properties application.properties
## Database Properties
spring.datasource.url = jdbc:sqlserver://localhost:1434;encrypt=false;databaseName=demo
spring.datasource.username = root
spring.datasource.password = root

## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.SQLServerDialect

# Hibernate ddl auto (create, create-drop, validate, update)


spring.jpa.hibernate.ddl-auto = update

R2S Academy - Internal Use 14


RESTful APIs (9)
Create Entity Class
• The @Entity annotation specifies that the class is an entity and is mapped to a database table.
• Example @Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = “employee_id")
private int id;

@Column(name = "last_name")
private String lastname;

@Column(name = "first_name")
private String firstname;

@Temporal(TemporalType.DATE)
@Column(name = "birth_date")
private Date birthdate;

@Column(name = “supervisor_id")
private int supervisor;

// Getters and Setters


}
R2S Academy - Internal Use 15
RESTful APIs (10)
Create JPA Data Repository
• @Repository annotation indicates that an annotated class is a repository,
which is an abstraction of data access and storage.
• Example
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
}

R2S Academy - Internal Use 16


RESTful APIs (11)
Create Rest Controllers
• @RestController annotation marks the class as controller, capable of handling the requests
• Example @RestController
@RequestMapping("/api/employee")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;

@GetMapping
public List<Employee> getAll() {
return employeeRepository.findAll();
}

@PostMapping
public Employee create(@RequestBody Employee employee) {
return employeeRepository.save(employee);
}
}
R2S Academy - Internal Use 17
RESTful APIs (12)
Build, Run, and Test
• Using Postman

R2S Academy - Internal Use 18


GraphQL
Introduction
• GraphQL is a query language for APIs. It allows applications to query and retrieve precisely
the data they need from a single endpoint, rather than having to send multiple requests to
various endpoints as in a RESTful API. // Fetch user details
• Example query {
GET /api/users/42
Response:
user(id: 42) { {
"username": "Mr. T",
username, "avatar": "http://example.com/users/42/pic.jpg",
avatar, }
posts { // Fetch user's posts
title, GET /api/users/42/posts
content, VS Response:
{
tags, "posts": [
date {
"title": "Hello World",
} "content": "Hi everyone!"
} }
]
} GraphQL } RESTful API
R2S Academy - Internal Use 19
Spring boot (1)
What is Spring boot
• Popular framework for building Java application
• Provides a large number of helper classes and annotations

R2S Academy - Internal Use 20


Spring boot (2)
Why using Spring boot
• Spring boot + Thymeleaf => Website

R2S Academy - Internal Use 21


Spring boot (3)
Why using Spring boot
• Spring boot => REST APIs

R2S Academy - Internal Use 22


Spring core (1)
What is Spring core
• Spring Core is the foundation of the Spring Framework for Java applications.
• It provides essential functionalities like Dependency Injection (DI),
Inversion of Control (IoC), and Bean management, which are crucial for
building loosely coupled and maintainable applications.

R2S Academy - Internal Use 23


Spring core (2)
What is DI
• Scenario: Imagine a scenario where you have a NotificationService that sends
notifications (e.g., emails, SMS) and a UserService that uses this service to send
notifications to users.

R2S Academy - Internal Use 24


Spring core (3)
DI
• Without DI This tight coupling makes the code less flexible. If you want to use a different notification service like
SMS in the future, you'd need to modify UserService to create an SMSNotificationService instance.
public class UserService {
// Directly create an EmailNotificationService instance
private NotificationService notificationService = new EmailNotificationService();

public void sendWelcomeNotification(String recipient, String message) {


notificationService.sendNotification(recipient, message);
}
}

public interface NotificationService {


void sendNotification(String recipient, String message); Scenario
}
Imagine a scenario where you have
a NotificationService that sends
public class EmailNotificationService implements NotificationService { notifications (emails, SMS) and a
public void sendNotification(String recipient, String message) { UserService that uses this service
// Code here to send notifications to users.
}
}

public class SMSNotificationService implements NotificationService {


public void sendNotification(String recipient, String message) {
// Code here
}
} R2S Academy - Internal Use 25
Spring core (4)
public class UserService { DI
// Directly create an EmailNotificationService instance
private NotificationService notificationService = new EmailNotificationService();

public void sendWelcomeNotification(String recipient, String message) {


notificationService.sendNotification(recipient, message);
}
} Using DI (Loose Coupling)

public class UserService { public class Main {


private NotificationService notificationService; //Dependency public static void main(String[] args) {
NotificationService notificationService = new EmailNotificationService();
UserService userService = new UserService(notificationService);
public UserService(NotificationService notificationService) {
userService.sendWelcomeNotification("[email protected]", "Hi");
this.notificationService = notificationService; }
} }

public void sendWelcomeNotification(String recipient, String message) { • We can inject a concrete implementation (e.g.,
notificationService.sendNotification(recipient, message); EmailNotificationService) through the constructor.
} • This makes UserService more flexible. You can easily switch
} between different notification services by providing a different
implementation during object creation.
R2S Academy - Internal Use 26
Spring core (5)
What is DI
• Dependency Injection (DI) is a technique in which the components of a class do not create
their dependencies but are provided from the outside.
public class UserService {
// Directly create an EmailNotificationService instance
private NotificationService notificationService = new EmailNotificationService();

public void sendWelcomeNotification(String recipient, String message) {


Do not create their notificationService.sendNotification(recipient, message);
dependencies }
}
Provided from the outside

public class UserService { Using DI


private NotificationService notificationService;
public class Main {
public UserService(NotificationService notificationService) { public static void main(String[] args) {
this.notificationService = notificationService; NotificationService notificationService = new EmailNotificationService();
} UserService userService = new UserService(notificationService);
userService.sendWelcomeNotification("[email protected]", "Hi");
public void sendWelcomeNotification(String recipient, String messagel) { }
notificationService.sendNotification(recipient, message); }
}
}
R2S Academy - Internal Use 27
Spring core (6)
What is IoC
• Example When the application is started, Spring Boot will scan and
@Service create beans from class annotated with this annotation.
public class UserService {
private final UserRepository userRepository;

@Autowired
IoC
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}

// Methods of UserService using userRepository


public List<User> getAllUsers() {
return userRepository.findAll();
}
}
In the example above:
• UserService is annotated with @Service. This informs Spring that this is bean.
• Beans are reusable components that represent objects in the application.
R2S Academy - Internal Use 28
Spring core (7)
What is IoC
• IoC manages the lifecycle of objects and provides dependencies to objects when needed.
• Lifecycle of objects: Initialization, Usage @Service
public class UserService {
• Example private final UserRepository userRepository;

The annotation @Service is used @Autowired


to mark UserService as a bean. public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
Use @Autowired which makes Spring // Methods of UserService using userRepository
automatically inject the UserRepository public List<User> getAllUsers() {
bean into the constructor of UserService return userRepository.findAll();
when it is initialized. => DI }
}
Spring IoC:
•Provide dependencies to beans in the application based on the "@Autowired" annotation.
•Scan and create beans from classes annotated with annotations such as "@Service", “@Repository”,…
R2S Academy - Internal Use 29
Maven (1)
Building a JDBC Application
• Without Maven
- Download the JDBC driver for your specific database (e.g., MySQL Connector/J for MySQL).
- Place the downloaded JAR file in your project directory or a location accessible by your class path.
• With Maven <project xmlns="http://maven.apache.org/POM/4.0.0">
<groupId>com.example</groupId>
<artifactId>jdbc-app</artifactId>
<version>1.0.0</version>

<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
</dependencies>
</project>
R2S Academy - Internal Use 30
Maven (2)
What is Maven
• Maven is a project management tool which centralizes project configuration
and simplifies the build process.
• Core functionalities
- Dependency Management: It manages project dependencies (external libraries
required by your project) by fetching them from remote repositories like Maven Central.
- Build Automation: Maven automates the process of compiling source code, packaging
compiled classes into distributable formats (JARs, WARs), and running tests.
- etc…

Remote Repository: https://mvnrepository.com/

R2S Academy - Internal Use 31


Maven (3)
Project

Project Structure pom.xml (Project Object Model)

R2S Academy - Internal Use 32


Keeping up those inspiration and the enthusiasm in the learning path.
Let confidence to bring it into your career path for getting gain the success as
your expectation.

Thank you
Contact
- Name: R2S Academy
- Email: [email protected]
Questions and Answers
- Hotline/Zalo: 0919 365 363
- Website: https://r2s.edu.vn
- Fanpage: https://www.facebook.com/r2s.tuyendung

R2S Academy - Internal Use 33

You might also like