0% found this document useful (0 votes)
21 views9 pages

Building REST APIs in Java

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)
21 views9 pages

Building REST APIs in Java

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)

Common questions

Powered by AI

Query Parameters are used to filter or search resources with multiple records through key-value pairs, typically appended to the URL's end (e.g., ?key=value). Path Parameters are used to identify specific single resources directly within the URL path (e.g., /resource/{id}). Use Query Parameters when you need to filter resources (e.g., retrieving a list with certain conditions) and Path Parameters when dealing with specific or unique resource retrievals (e.g., the details of an individual item).

Best practices for designing HTTP endpoints in a RESTful API include using clear and consistent naming conventions, leveraging nouns rather than verbs to describe resources, and designing endpoints to correspond closely with business logic. Endpoints should be stateless, ensuring each request from a client contains all necessary information to process the request. This aligns with HTTP standards and REST principles, simplifying integration and reducing errors. Structurally, using nested resources and leveraging appropriate HTTP methods enhances clarity and intuitive use. Proper endpoint design increases API usability by making it more intuitive and predictable for developers, while statelessness and consistency enhance scalability by reducing server-side session management load and simplifying horizontal scaling strategies .

When developing a RESTful API in Java using JAX-RS, considerations include choosing an implementation (e.g., Jersey, RESTEasy), correctly using annotations like @GET, @POST, and @Path for method binding and path mapping, and managing media types with 'produces' and 'consumes'. Compared to Spring, which uses annotations like @RestController, @GetMapping, and @PostMapping, Spring's framework provides integrated support for RESTful services within its MVC context and additional tooling such as Spring Boot for rapid development. JAX-RS APIs tend to offer more direct control over HTTP details, while Spring Framework's abstraction might simplify development with less code .

The @RestController annotation in Spring Boot simplifies the creation of RESTful services by combining the functionalities of @Controller and @ResponseBody, automatically serializing response data into JSON or XML formats without manual configuration. This abstraction frees developers from managing low-level response objects and content negotiation, as opposed to traditional servlet programming which requires additional logic for handling HTTP responses and data serialization explicitly. Furthermore, Spring Boot's integration with its Web MVC framework facilitates rapid development with minimal boilerplate code by leveraging annotations like @GetMapping, @PostMapping, etc., reducing the need for extensive configuration .

The 'produces' attribute in RESTful services specifies the media types that a method can return in response, indicating the format of the response body (e.g., application/xml, application/json). The 'consumes' attribute specifies the media formats a method can process when receiving request data, defining the expected format of the request body. During a request-response cycle, the client sets the 'Content-Type' header (corresponding to 'consumes') to indicate the sent data's format, and the 'Accept' header (corresponding to 'produces') to specify the desired format for response data. The server uses message converters to align the response format with the client's 'Accept' header choice .

Swagger provides several advantages in REST API development. It generates interactive and user-friendly API documentation, enabling developers and consumers to understand API endpoints easily. Additionally, Swagger UI offers an interface for testing API endpoints directly, assisting in development and debugging processes by allowing immediate feedback on requests without writing additional client code. Swagger standardizes API documentation, ensuring consistent communication and streamlined integration for different services and clients .

HTTP status codes in RESTful services convey the result of the request processing, providing clear feedback to the client about the success or failure of the request. Common codes include 200 (OK) for successful requests, 201 (Created) when a new resource is created, 400 (Bad Request) for client errors, and 404 (Not Found) when a resource is not available. They enhance API reliability by standardizing error reporting, allowing clients to handle different response scenarios predictably and improve communication consistency between services .

Using an HTTP POST request for updates is generally not recommended because POST is semantically intended for creating new resources. This usage contradicts the typical RESTful operation mapping, where PUT or PATCH are the appropriate methods for updating existing resources. PUT is explicitly designed to update a resource completely, and PATCH is used for partial updates. Using POST for updates can lead to confusion, potential misuse of HTTP protocol semantics, and unexpected behavior in client-server interactions, breaking the conventional REST architecture principles .

Using both 'produces' and 'consumes' attributes in a REST API method is crucial for supporting multiple content types because it defines clear expectations around data formats both for incoming requests and outgoing responses. This dual specification helps ensure that APIs can handle various client requests and respond correctly in formats such as JSON or XML. It also facilitates smooth content negotiation between the client and server, enhancing compatibility and reliability across different client environments and supporting widespread use cases .

RESTful services utilize HTTP methods to perform operations on resources. The HTTP methods map to CRUD (Create, Read, Update, Delete) operations as follows: POST is used to create new resources, mapping to 'Create'; GET retrieves resources and maps to 'Read'; PUT is for updating existing resources, mapping to 'Update'; DELETE removes resources, mapping to 'Delete'. These mappings adhere to standard HTTP protocol semantics, facilitating interoperability and compliance with REST principles .

You might also like