0% found this document useful (0 votes)
10 views14 pages

Developing REST APIs with Java

The document provides a comprehensive guide on developing REST APIs using Java, specifically with JAX-RS and Spring Boot. It covers various aspects such as HTTP methods, request and response structures, handling query and path parameters, and the use of Swagger for API documentation. Additionally, it includes examples of CRUD operations with a MySQL database and the use of embedded databases like H2 for development purposes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views14 pages

Developing REST APIs with Java

The document provides a comprehensive guide on developing REST APIs using Java, specifically with JAX-RS and Spring Boot. It covers various aspects such as HTTP methods, request and response structures, handling query and path parameters, and the use of Swagger for API documentation. Additionally, it includes examples of CRUD operations with a MySQL database and the use of embedded databases like H2 for development purposes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

What is Disributed Application

What is Intereoperability
What is HTTP Protocol
HTTP Methods
HTTP Status Codes
HTTP Request Structure
HTTP Response Structure
Working with XML and JAX-B
Working with JSON and Jackson

+++++++++++++++++++++++++++++++
How to develop REST API using Java
+++++++++++++++++++++++++++++++++

-> To develop RESFul Services/ REST APIs using java SUN Microsystem released 'JAX-
RS' API

-> JAX-RS api having 2 implementations

1) Jersey (Sun Microsystems)


2) REST Easy (JBOSS)

Note: We can develop RESTFul Services using any one of the above implementation

-> Spring framework also provided support to develop RESTFul Services using 'Spring
Web MVC' module.

+++++++++++++++++++++++++
RESTFul Services Architecture
+++++++++++++++++++++++++

-> We will have 2 actors in RESTful services

1) Provider / Resource

2) Consumer / Client

-> The application which is providing services to other applications is called as


Provider or Resource application

-> The application which is accessing services from other applications is called as
Consumer or Client application

-> Client application and Resource application will exchange data in intereoperable
format (like XML & JSON)

request
client app <------------------------> resource app
response

Note: RESTful Services are used to develop B2B communications (No presentation
logic, No view Resolver)

+++++++++++++++++++++++++++++++++++
Develop First REST API Using Spring Boot
+++++++++++++++++++++++++++++++++++

1) Create Spring starter application with below dependencies

a) web-starter
b) devtools

2) Create RestController with Required methods

Note: To represent java class as Rest Controller we will use @RestController


annotation

@RestController = @Controller + @ResponseBody

Note: Every RestController method should be binded to HTTP Protocol method

Ex: @GetMapping, @PostMapping, @PutMapping & @DeleteMapping

3) Run the application and test it.

Note: To test REST APIs we will use POSTMAN tool (It is free)

Note: Download postman tool to test our REST API functionality

+++++++++++++++++++++++++++++++++++
@RestController
public class WelcomeRestController {

@GetMapping("/welcome")
public ResponseEntity<String> getWelcomeMsg() {
String respPayload = "Welcome to Ashok IT";
return new ResponseEntity<>(respPayload, [Link]);
}

@GetMapping("/greet")
public String getGreetMsg() {
String respPayload = "Good Morning..!!";
return respPayload;
}
}
+++++++++++++++++++++++++++++++++++

Note: GET Request will not contain Request Body to send data

-> We can use Query Params and Path Params to send data in GET Request

-> Query Params & Path Params will represent data in URL directlry

++++++++++++++
Query Params
++++++++++++++

-> Query Params are used to send data to server in URL directly

-> Query Params will represent data in key-value format


-> Query Params will start with '?'

-> Query Parameters will be seperated by '&'

-> Query Parameters should present only at the end of the URL

Ex: [Link]/courses?name=SBMS&trainer=Ashok

-> To read Query Parameters from the URL we will use @RequestParam annotation

@GetMapping("/welcome")
public ResponseEntity<String> getWelcomeMsg(@RequestParam("name") String
name) {
String respPayload = name + ", Welcome to Ashok IT";
return new ResponseEntity<>(respPayload, [Link]);
}

URL : [Link]

+++++++++++++++++++++++++++++++++
Working with 2 Query Params in URL
+++++++++++++++++++++++++++++++++++
@RestController
public class CourseRestController {

@GetMapping("/course")
public ResponseEntity<String> getCourseFee(@RequestParam("cname") String
cname,
@RequestParam("tname") String tname) {

String respBody = cname + " By " + tname + " Fee is 7000 INR";

return new ResponseEntity<>(respBody, [Link]);

}
}

URL : [Link]

++++++++++++++++++++++++++++
Path Parameter or URI variables
+++++++++++++++++++++++++++++

-> Path Parameters are also used to send data to server in URL

-> Path Params will represent data directley in URL (no keys)

-> Path Params can present anywhere in the URL

-> Path Params will be seperated by / (slash)

-> Path Params should be represented in Method URL pattern (Template Pattern)
Ex: [Link]/courses/{cname}/trainer/{tname}

-> To read Path Parameters we will use @PathVariable annotation

@RestController
public class BookRestController {

@GetMapping("/book/{name}")
public ResponseEntity<String> getBookPrice(@PathVariable("name") String name)
{

String respBody = name + " Price is 400 $";

return new ResponseEntity<>(respBody, [Link]);


}

@GetMapping("/book/name/{bname}/author/{aname}")
public ResponseEntity<String> getBook(@PathVariable("bname") String bname,
@PathVariable("aname") String aname) {

String respBody = bname + " By " + aname + " is out of stock";

return new ResponseEntity<>(respBody, [Link]);


}
}

URL-1 : [Link]

URL-2 : [Link]

+++++++++++++++++++++++++++++++++++++++
Q) When to use Path Params & Query Params ?
++++++++++++++++++++++++++++++++++++++++

-> To retrieve more than one record/resource we will use Query Params (filtering)

-> To retreive specific/unique record we will use Path Params (single)

################
What is Produces
#################

-> "produces" is a media type


-> It represents the response formats supported by REST Controller Method
-> One method can support multiple response formats (xml and json)

produces = { "application/xml", "application/json" }

-> Client should send a request with "Accept" http header


-> Accept header represents in which format client expecting response from the REST
api
-> Based on Accept header value 'Message Converter' will convert the response into
client expected format
@Data
@XmlRootElement
@NoArgsConstructor
@AllArgsConstructor
public class Product {

private Integer pid;


private String pname;
private Double price;

@RestController
public class ProductRestController {

@GetMapping(
value = "/product",
produces = { "application/xml", "application/json" }
)
public ResponseEntity<Product> getProduct() {

Product p1 = new Product(101, "Monitor", 8000.00);

return new ResponseEntity<>(p1, [Link]);


}

@GetMapping("/products")
public ResponseEntity<List<Product>> getProducts(){

Product p1 = new Product(101, "Monitor", 8000.00);


Product p2 = new Product(102, "RAM", 6000.00);
Product p3 = new Product(103, "CPU", 15000.00);

List<Product> products = [Link](p1,p2,p3);

return new ResponseEntity<>(products, [Link]);


}
}

##############################
Working with HTTP POST Request
#############################

-> HTTP POST request is used to create new resource/record at server

-> POST request contains request body

-> Client can send data to server in Request Body

-> To bind Rest Controller method to POST request we willl use @PostMapping

-> To read data from Requet body we will use @RequestBody annotation

-> "consumes" represents in which formats method can take input

-> "Content-Type" header represents in which format client sending data in request
body.
@Data
@XmlRootElement
public class Book {

private Integer id;


private String name;
private Double price;

}
---------------------------
@RestController
public class BookRestController {

@PostMapping(
value = "/book",
consumes = { "application/json", "application/xml" }
)
public ResponseEntity<String> addBook(@RequestBody Book book) {
[Link](book);

// logic to store in DB

String msg = "Book Added Succesfully";

return new ResponseEntity<String>(msg, [Link]);


}
}

----------------
{
"id" : 101,
"name" : "Java",
"price" : 450.00
}

------------------------

-> produces vs consumes

-> Content-Type vs Accept

-> produces attribute represents in which formats Method can provide response data
to clients

-> consumes attribute represents in which formats Method can take request data from
clients

-> Accept header represents in which format client expecting response from REST API

-> Content-Type header represents in which format client is sending request data to
REST API

Note: We can use both Consumes & Produces in single REST API method.
++++++++++++++++++++++++++++++++++++++++++++++++++
Requirement : Develop IRCTC REST API to book a train ticket
++++++++++++++++++++++++++++++++++++++++++++++++++++

-> To develop any REST API first we have to understand the requirement

-> Identify input / request data

-> Identify output / response data

-> Create request & response binding classes

-> Create REST Controller with required methods.

-> Test REST API methods behaviour using Postman

@Data
public class PassengerInfo {

private String name;


private Long phno;
private String jdate;
private String from;
private String to;
private Integer trainNum;

@Data
public class TicketInfo {

private Integer ticketId;


private String pnr;
private String ticketStatus;

@RestController
public class TicketRestController {

@PostMapping(
value = "/ticket",
produces = {"application/json"},
consumes = {"application/json"}
)
public ResponseEntity<TicketInfo> bookTicket(@RequestBody PassengerInfo
request){
[Link](request);

//logic to book ticket


TicketInfo tinfo = new TicketInfo();
[Link](1234);
[Link]("JLJL6868");
[Link]("CONFIRMED");
return new ResponseEntity<>(tinfo, [Link]);
}
}

-------------------------------
{
"name" : "Ashok",
"phno" : 12345678,
"jdate" : "05-08-2022",
"from" : "hyd",
"to" : "pune",
"trainNum" : 8574
}

{
"ticketId": 1234,
"pnr": "JLJL6868",
"ticketStatus": "CONFIRMED"
}

#################
HTTP PUT Request
#################

-> PUT request is used to update an existing record / resource at server

-> PUT Request can take data in URL and in Request Body

-> To bind our method to PUT request we will use @PutMapping

@PutMapping("/ticket")
public ResponseEntity<String> updateTicket(@RequestBody PassengerInfo
request){
[Link](request);
//logic to update ticket
return new ResponseEntity<>("Ticket Updated", [Link]);
}

####################
HTTP DELETE Request
####################

-> DELETE request is used to delete an existing record / resource at server

-> DELETE Request can take data in URL and in Request Body

-> To bind our method to DELETE request we will use @DeleteMapping

@DeleteMapping("/ticket/{ticketId}")
public ResponseEntity<String> deleteTicket(@PathVariable("ticketId") Integer
ticketId){
//logic to delete the ticket
return new ResponseEntity<>("Ticket Deleted", [Link]);
}
------------------------------------------
What is RestController ?
REST Controller Methods
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping

Query Params
Path Params
Request Body
Response Body

@RequestParam
@PathVariable
@RequestBody

produces
consumes
Accept
Content-Type

Message Converters

ResponseEntity

Q) Can we write the logic to update a record in POST request method ?

Ans) Yes, we can do it but not recommended. We need to follow HTTP Protocol
standards while developing REST API.

+++++++++
Swagger
+++++++

-> Swagger is used to generate documentation for REST APIs

-> Swagger UI is used to test REST API with user interface

Assignment : [Link] (watch Swagger video & practise it)

-> Add below 2 dependencies in [Link] file

<dependency>
<groupId>[Link]</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>

<dependency>
<groupId>[Link]</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>
-> Add below property in [Link] file

[Link]-strategy = ANT_PATH_MATCHER

-> Create Swagger Config class like below

@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket apiDoc() {

return new Docket(DocumentationType.SWAGGER_2)


.select()
.apis([Link]("[Link]
st"))
.paths([Link]())
.build();
}
}

-> We can access swagger ui using below URL

[Link]

-> We can access swagger documentation using below url

[Link]

++++++++++++++++++++++++++++++++++++++++++++
CRUD Operations using REST API with MySQL DB
++++++++++++++++++++++++++++++++++++++++++++

-> Download & install MySQL Database (DB Server)

-> Download & install MySQL Workbench (DB client)

SQL Queries
DB client ----------------------------> DB server

-> Develop REST API using Layered Architecture

1) Web Layer

2) Business / Serice Layer

3) DAO Layer

@Data
@Entity
@Table(name = "BOOK_DTLS")
public class Book {

@Id
@GeneratedValue(strategy = [Link])
@Column(name = "BOOK_ID")
private Integer bookId;

@Column(name = "BOOK_NAME")
private String bookName;

@Column(name = "BOOK_PRICE")
private Double bookPrice;

public interface BookRepository extends JpaRepository<Book, Serializable>{

public interface BookService {

public String upsertBook(Book book);

public List<Book> getAllBooks();

public String deleteBook(Integer bookId);


}

@Service
public class BookServiceImpl implements BookService {

private BookRepository repository;

public BookServiceImpl(BookRepository repository) {


[Link] = repository;
}

@Override
public String upsertBook(Book book) {

Integer bookId = [Link]();

[Link](book);

[Link](book);

[Link](book);

if (bookId == null) {
return "Record Inserted";
} else {
return "Record Updated";
}
}

@Override
public List<Book> getAllBooks() {
return [Link]();
}

@Override
public String deleteBook(Integer bookId) {
[Link](bookId);
return "Book Deleted";
}
}

@RestController
public class BookRestController {

@Autowired
private BookService service;

@PostMapping("/book")
public ResponseEntity<String> addBook(@RequestBody Book book) {
String msg = [Link](book);
return new ResponseEntity<>(msg, [Link]);
}

@GetMapping("/books")
public ResponseEntity<List<Book>> getAllBooks() {
List<Book> allBooks = [Link]();
return new ResponseEntity<>(allBooks, [Link]);
}

@PutMapping("/book")
public ResponseEntity<String> updateBook(@RequestBody Book book) {
String msg = [Link](book);
return new ResponseEntity<>(msg, [Link]);
}

@DeleteMapping("/book/{bookId}")
public ResponseEntity<String> deleteBook(@PathVariable Integer bookId) {
String msg = [Link](bookId);
return new ResponseEntity<>(msg, [Link]);
}
}

-----------------------------------------------------------------------------------
---------------------------------------------------------------------

######################
Embedded Database (H2)
######################

-> Embedded Databases are temporary databases / in-memory databases

-> Embedded Databases are used for POC development (Proof of concept)

-> We no need to download and install embedded databases

-> Embedded Databases will come along with our application by adding one dependency

-> When we start application then embedded db will start and when we stop the
application then embedded db will be stopped
Note: Data is not permenent in the embedded db (when we stop the application we
will loose the data)

Note: In Memory DBs are not used for realtime project development in the company

-> We can use H2 DB as an in-memory db for practise purpose

-> Add below dependency in [Link] to

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

-> Configure H2 Datasource properties

[Link]=jdbc:h2:mem:testdb
[Link]=sa
[Link]=sa
[Link]-class-name=[Link]

-> Run the application and access h2-console using below URL

[Link]

Common questions

Powered by AI

Query parameters are used to send data to the server in a URL directly, represented in a key-value format. They start with a '?' and are separated by '&'. They are typically used for filtering when retrieving more than one record or resource . Path parameters, on the other hand, are used to send data directly in the URL without keys, separated by slashes (/). They are used to retrieve a specific or unique record . Thus, query parameters are suitable for optional data and filtering, whereas path parameters are used for mandatory data and identification of specific resources.

POST requests are recommended for creating new resources because they are designed to send data to the server and add a new entry to a particular resource or collection . Using POST for updates can technically be done but is not recommended because it violates HTTP protocol standards, which prescribe using PUT requests for updating existing resources . Using POST for updates can lead to ambiguity in terms of resource identification and lifecycle, potentially disrupting idempotency, which is a crucial aspect of RESTful operations . Hence, using methods that align with their intended purpose ensures clear, maintainable, and scalable API design.

Swagger enhances REST API development and testing by providing a comprehensive documentation solution that includes an interactive user interface for testing API endpoints . To integrate Swagger with a Spring Boot application, developers must add specific dependencies such as 'springfox-swagger2' and 'springfox-swagger-ui' into the project's pom.xml file . A Swagger configuration class annotated with '@Configuration' and '@EnableSwagger2' is also needed to set up the documentation with the API's base package using the 'Docket' bean . This setup allows developers to visualize and test API endpoints interactively through the Swagger UI, improving usability and debugging.

The '@RestController' annotation in a Spring Boot application indicates that the class is a controller where each method returns a domain object instead of a view, which is typical for RESTful services. It combines the '@Controller' and '@ResponseBody' annotations . This annotation facilitates the development of RESTful APIs by making it easier to bind HTTP methods (GET, POST, PUT, DELETE) to Java methods using annotations like '@GetMapping', '@PostMapping', '@PutMapping', and '@DeleteMapping' . It directly handles HTTP requests and responses in a standardized way.

In a RESTful web service, media type negotiation is handled through the 'produces' and 'consumes' attributes, which dictate the media types that a service method can deliver and accept, respectively . In Spring Boot, these are directly linked to the HTTP 'Accept' and 'Content-Type' headers, ensuring that the server only processes requests in expected formats and delivers responses in a format the client can handle. Practically, this allows API clients to specify the format they require (e.g., XML or JSON), which enhances interoperability between different systems. It also assures consistent and accurate data handling, maintaining integrity across diverse client applications, particularly in environments with multiple data interchange requirements. This adherence avoids miscommunication and ensures API reliability.

The 'Content-Type' HTTP header indicates the media type of the resource being sent to the server, specifying the format of the request data. The 'Accept' HTTP header, conversely, indicates the media types that the client is willing to accept in the response . The 'produces' attribute in a REST Controller method specifies the media types the method can generate in the response, aligning it with the 'Accept' header. The 'consumes' attribute indicates the media types the method can accept for processing, aligning it with the 'Content-Type' header . These headers and attributes together ensure correct interpretation and transformation of data formats between client and server, facilitating smooth, interoperable communication.

Using 'ResponseEntity' in RESTful web services is effective as it provides greater control over the HTTP response, allowing developers to define not just the body, but also the status code and headers . This flexibility improves response handling by making it easier to adhere to REST principles and return precise status messages that accurately convey the result of the operation to the client. In Spring applications, 'ResponseEntity' facilitates clean and concise representation of responses, simplifies error handling, and enhances API documentation clarity, enabling better client-side integration and debugging. By supporting a more informative exchange between client and server, it leads to more robust and reliable RESTful services.

RESTful Services using JAX-RS and those built with the Spring Web MVC differ structurally and functionally primarily in their approach and ecosystem integration. JAX-RS is a specification that provides a set of interfaces and annotations to create RESTful web services in Java, with implementations like Jersey and RESTEasy focusing on Java EE standards . In contrast, Spring Web MVC offers a full-stack framework approach heavily integrated with Spring's other features like dependency injection, aspects, and security, enabling faster development due to readily available tools and simplified configuration . Functionally, Spring provides additional options for transaction management and security, which can simplify complex enterprise applications, whereas JAX-RS focuses on the core REST concepts, which might require additional components to handle cross-cutting concerns.

Embedded databases like H2 are important for REST API development because they are lightweight, easy to set up, and do not require installation, making them ideal for rapid prototyping or proof of concept (POC) development . Their ephemeral nature, where data isn’t preserved post-application shutdown, makes them unsuitable for production environments where data persistence and durability are critical . While they facilitate quick testing and development iterations without extensive database setup, their lack of scalability and persistence render them inappropriate for handling real-time, live applications within an enterprise where robust data management is essential.

The JAX-RS API, which is used for developing RESTful services, has two main implementations: Jersey (by Sun Microsystems) and RESTEasy (by JBOSS). In addition to these, the Spring framework also provides support for developing RESTful services through its 'Spring Web MVC' module . While Jersey and RESTEasy are direct implementations of the JAX-RS specification primarily focusing on Java-based solutions, the Spring framework integrates REST into its existing ecosystem, providing additional features such as dependency injection, aspect-oriented programming, and integration with other Spring components.

You might also like