09 01 Services Slides
09 01 Services Slides
Building Services
Web Services; REST; Spring Boot
What is a service?
• A service is software that provides capabilities to
other software.
2
fi
ff
Why distribute services?
It can be useful to split processing across multiple systems:
• Resource sharing. We often need to share resources across users. For example, storing
our customer data in shared databases that everyone in the company can access.
• Performance. It can be more cost e ective to have one machine running the bulk of our
processing, while cheaper/smaller systems can be used to access that shared machine.
It can also be cheaper to spread computation across multiple systems, running tasks in
parallel. Distributed architectures provide exibility to align the processing capabilities
with the task to be performed.
• Scalability. If designed correctly, distributing our work across multiple systems can allow
us to grow our system to meet high demand. Amazon for example, needs to ensure that
their systems remain responsive, even in times of heavy load (e.g. holiday season).
3
ff
ff
fl
Distributed Architectures
4
Client-Server
A client-server architecture is a model where a server provides capabilities to clients.
• Client − The process that issues a request to the second process i.e. the server.
From the point of view of the user, this is the application that they interact with.
• Server − The process that receives and handles a request, and replies to the client.
Advantages
5
ff
Multi-Tier
A multi-tier architecture (aka 2-tier, 3-tier or layered) separates an
application into separate tiers or areas of concerns, often with each
tier deployed on a separate computer.
3. The bottom layer is the Data tier, which handles access, storage
and management of the underlying data (i.e. database, or other).
Advantages
• Service contract: there should be an agreed upon interface for accessing a service.
• Longevity: services should be designed to be long-lived (long-running).
• Autonomy: services should work independently of one another.
• Stateless: services should not track state, but either return a resulting value or throw
an exception.
Advantages
• Service are not tied to any one programming language, platform or set of
technologies.
Advantages
9
How do components communicate?
• Services of any type need to communicate with the client, and with one another.
• We need some protocols: how the data is structured, transmitted, validated.
• Many service architectures rely on heavyweight proprietary messaging protocols. e.g. RPC.
• These protocols are often tightly coupled to the underlying implementation.
• Early system focused on invoking remote functions - far too low level!
• The preferred approach, especially with microservices is to use a lightweight protocol.
• Request-response model
• Loose coupling between client and service Realization that we’re already
doing this with the web….
• Well-formed, lightweight messages
10
HTTP
The Hypertext Transfer Protocol (HTTP) is an application layer protocol that supports serving documents, and
processing links to related documents, from a remote service.
HTTP functions as a request–response protocol:
• A web browser is a typical client, which the user is accessing. A web server would be a typical server.
• The user requests content through the browser, which results in an HTTP request being sent to the server.
• The server, which provides resources such as HTML les and other content or performs other functions on
behalf of the client, returns a response message to the client that includes status, and possibly data.
11
HTTP Request Methods
HTTP de nes request methods to indicate the desired action, which will be taken on some resource (whatever the endpoint
or URL represents). Often, the resource corresponds to a le or the output of an executable residing on the server.
• GET
The GET method requests that the target resource transfers a representation of its state. GET requests should only
retrieve data and should have no other e ect.
• HEAD
The HEAD method requests that the target resource transfers a representation of its state, like for a GET request, but
without the representation data enclosed in the response body. Uses include looking whether a page is available
through the status code, and quickly nding out the size of a le.
• POST
The POST method requests that the target resource processes the representation enclosed in the request according to
the semantics of the target resource. For example, it is used for posting a message to an Internet forum, or completing
an online shopping transaction.
• PUT
The PUT method requests that the target resource creates or updates its state with the state de ned by the
representation enclosed in the request. A distinction to POST is that the client speci es the target location on the
server.
• DELETE
The DELETE method requests that the target resource deletes its state.
12
fi
fi
ff
Web services
A web service is a service that is built using web technologies, which serves up content
using web protocols and data formats (e.g. JSON).
• Use HTTP as the basis for a more generalized service protocol that can serve up a
broader range of data.
• Leverage the ability of web servers to handle HTTP requests in a very e cient manner,
with the ability to scale to very large numbers of requests.
What we’re missing are some guidelines that we can use on how to structure HTTP for
generic requests, and make it useful for more than just a browser.
13
REST
14
REST
REpresentational State Transfer (REST), is a software architectural style that de nes a set of
constraints for how the architecture of an Internet-scale system, such as the Web, should
behave.
• The term “RESTful Services” is commonly used to describe services built using standard
web technologies that adheres to these design principles.
^ Roy was also one of the principle authors of the HTTP protocol, and co-founded the Apache server project.
15
16
REST Principles
1. Client-Server. By splitting responsibility into a client and service, we
decouple our interface and allow for greater exibility in how our service
is deployed.
3. Cacheable. With stateless servers, the client has the ability to cache
responses under certain circumstances which can improve performance.
5. Stateless. The service does not retain state i.e. it's idempotent. Every
request that is sent is handled independently of previous requests. That
does not mean that we cannot store data in a backing database, it just
means that we have consistency in our processing.
17
fl
Request Methods w. REST
For your service, you de ne one or more endpoints (URLs). Think of an endpoint as a function - you interact
with it to make a request to the server. Examples:
• https://localhost:8080/messages
• https://cs.uwaterloo.ca/asis
To use a service, you format a request using one of these request types and send that request to an endpoint.
• GET: Use the GET method to read data. GET requests are safe and idempotent.
• POST: Use a POST request to STORE data i.e. create a new record in the database, or underlying data
model. Use the request payload to include the information that you want to store. You have a choice of
content types (e.g. multipart/form-data or x-www-form-urlencoded or raw application/json, text/plain...)
18
fi
API Suggestions
Here's some guidelines on using REST to create a web service [Cindrić 2021].
It's easier to use, read and write, and it’s faster than XML. Every meaningful
programming language and toolkit already supports it.
Use nouns instead of verbs and use plural instead of singular form. e.g.
19
API Guidelines
3. Be Consistent
If you de ne a JSON structure for a record, you should always use that structure:
avoid doing things like omitting empty elds (instead, return then as named
empty arrays).
Good 👍 Bad 👎
•GET /users •GET /user/23
•POST /users •GET /listAllUsers
•GET /users/23 •POST /user/create
•PUT /users/23 •PUT /updateUser/23
•DELETE /users/23 •GET /userComments/23
•GET /users/23/comments
20
fi
fi
Spring Boot
21
What is Spring Boot?
Spring is a popular Java framework for building web services.
In the same way that JavaFX provides a framework for building GUIs on desktop, Spring
provides a framework for building web services. It greatly reduces the e ort required*.
Spring is opinionated: it provides a strict framework and you are expected to add classes,
and customize behaviour, to what is provided.
Spring is the framework, and Spring Boot is a set of tools for generating a project with all
of the required dependencies. We’ll walk through setting up a simple Spring Boot
application. The steps are typically:
• Visit start.spring.io and set parameters for your project. Generate and download the project les.
• Alternatively, use the Spring project wizard in IntelliJ. Set the parameters for your project (Kotlin, Gradle)
and follow instructions to generate an IntelliJ IDEA project.
A Spring Boot project looks like a normal project built on Gradle, but it’s got a
number of dependencies already imported and the framework is setup. It can be
executed but won’t do anything interesting yet.
24
Adding a Controller /service/spring-server-basic
/service/spring-client
@SpringBootApplication
class DemoApplication
The controller manages the endpoints, and
fun main(args: Array<String>) { requests that are made to our service.
runApplication<DemoApplication>(*args)
}
@Service
class MessageService(val db: MessageRepository) { Dependency injection of a MessageRepository
which the framework will will manage.
fun findMessages(): List<Message> = db.findMessages()
interface MessageRepository : CrudRepository<Message, String>{ A repository represents the data store. The
framework will automatically use H2 and
@Query("select * from messages") create methods for us to call. e.g. db.save
fun findMessages(): List<Message>
}
@Table("MESSAGES")
A table will also be created in the database,
data class Message(@Id val id: String?, val text: String)
using the structure from our data class.
26
Magic!
JPA automatically created a table for our Repository, re ecting the structure of the Message data class.
27
fl
Testing your service
You can create and run HTTP requests
from within IntelliJ IDEA.
28
Client Requests
29
Making an HTTP Request
How do we actually use our service? Kotlin (and Java) includes libraries that allow you to structure and
execute requests from within your application.
The HttpRequest class uses a builder to let us supply as many optional parameters as we need:
32
Resources
33
Resources
• Jan Bodnar. 2022. Kotlin HTTP GET/POST request. https://zetcode.com/kotlin/getpostrequest/
• Vedran Cindrić. 2021. The 10 REST Commandments. https://treblle.com/blog/the-ten-rest-commandments
• Matt Greencroft. 2018. Building Spring Boot Applications with the Kotlin Programming Language. Manning Publishing. Video.
• JetBrains. 2021. Create a RESTful web service with a database using Spring Boot – tutoria . https://kotlinlang.org/docs/jvm-
spring-boot-restful.html
• JetBrains. Kotlin Server Side. https://kotlinlang.org/lp/server-side
• Love Sharma. 2021. Principles & Best Practices of REST API Design. https://blog.devgenius.io/best-practice-and-cheat-
sheet-for-rest-api-design-6a6e12dfa89f
• arjuna sky kok. 2021. Kotlin and Spring Boot: Getting Started. https://www.raywenderlich.com/28749494-kotlin-and-spring-
boot-getting-started
• VMware. 2022. (Spring) Accessing Data with JPA. https://spring.io/guides/gs/accessing-data-jpa/
• VMware. 2022. Building web applications with Spring Boot and Kotlin. https://spring.io/guides/tutorials/spring-boot-kotlin/
• VMware. 2022. Spring Boot Reference Documentation. https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
#legal
34