0% found this document useful (0 votes)
42 views41 pages

REST vs SOAP: Key Differences Explained

The document outlines key differences between REST and SOAP, authentication and authorization, JWT tokens in Spring, CORS, CSRF attacks, and methods for consuming REST APIs. It provides code examples, real-time use cases, and best practices for implementing security and data transmission in web applications. Additionally, it discusses the appropriate use of HTTP methods for sending data to servers.

Uploaded by

Yogesh Mungase
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)
42 views41 pages

REST vs SOAP: Key Differences Explained

The document outlines key differences between REST and SOAP, authentication and authorization, JWT tokens in Spring, CORS, CSRF attacks, and methods for consuming REST APIs. It provides code examples, real-time use cases, and best practices for implementing security and data transmission in web applications. Additionally, it discusses the appropriate use of HTTP methods for sending data to servers.

Uploaded by

Yogesh Mungase
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

1) Difference Between REST and SOAP ?

Difference between REST and SOAP (with code example & real-
time use case)

✅ Definition & Protocol

REST (Representational SOAP (Simple Object Access


Feature
State Transfer) Protocol)

Uses HTTP, SMTP, or other


Protocol Uses HTTP protocol
protocols
Data Format Supports JSON, XML, etc. Supports only XML
Style Architectural style Protocol-based standard
Performance Lightweight, fast Heavy, more bandwidth required

✅ Code Example

REST Example (JSON over HTTP):

http
CopyEdit
GET /api/employees/101 HTTP/1.1
Host: [Link]

Response:

json
CopyEdit
{
"id": 101,
"name": "John Doe",
"position": "Developer"
}
SOAP Example (XML over HTTP):

xml
CopyEdit
<soapenv:Envelope
xmlns:soapenv="[Link]
xmlns:emp="[Link]
<soapenv:Header/>
<soapenv:Body>
<emp:getEmployee>
<emp:id>101</emp:id>
</emp:getEmployee>
</soapenv:Body>
</soapenv:Envelope>

✅ Real-Time Use Case

Use Case REST SOAP


✅ Preferred due to
❌ Not suitable due to XML
Mobile & Web Apps lightweight JSON & fast
overhead
load
✅ SOAP preferred due to
Enterprise Apps like
❌ Less secure by default WS-Security and strict
Banking
contracts

✅ Summary

• Use REST when you want fast, lightweight, and scalable APIs
(e.g., Mobile apps, Microservices).
• Use SOAP when you need formal contracts, security, and
transactional reliability (e.g., Payment gateway, Banking
software).

==================================================
2) Difference Between Authentication and
Authorization ?
✅ Difference Between Authentication and Authorization

Feature Authentication Authorization


Determines what the user is
Definition Verifies who the user is
allowed to do
Purpose Confirms identity Grants access rights
Happens before
When it occurs Happens after authentication
authorization
Uses credentials like Uses roles, permissions,
Data involved
username/password access controls
Login with email & User with “Admin” role can
Example
password delete records

✅ Real-Time Example

• You log into a banking app with a username & password →


Authentication
• After login, you can view balance but not approve loans →
Authorization

✅ Spring Security Flow

java
CopyEdit
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN") // ←
Authorization
.anyRequest().authenticated() // ← Authentication
.and()
.formLogin(); // ← Authentication mechanism
}

🔑 Summary

• Authentication: "Are you who you claim to be?"


• Authorization: "Are you allowed to do what you're trying to
do?"

==================================================

3) What is JWT token in Spring ?


✅ What is JWT Token in Spring?

JWT (JSON Web Token) is a compact, secure way to transmit


information between two parties — especially used in Spring Boot
for stateless authentication in REST APIs.

✅ Structure of JWT

A JWT has three parts, separated by dots (.):

css
CopyEdit
[Link]

Example:

CopyEdit
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJ1c2VySWQiLCJpYXQiOjE2Mj...
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
✅ How JWT Works in Spring Boot

1. User logs in → Sends username & password


2. Server authenticates → Creates a JWT token and sends it back
3. Client stores the token (e.g., in browser localStorage)
4. For every API request, client sends token in Authorization
header:

makefile
CopyEdit
Authorization: Bearer <token>

5. Server validates token before processing request (no session


needed)

✅ Why JWT is Used in Spring Boot

• Stateless authentication (no session)


• Scalable in microservices
• Compact and URL-safe
• Can include claims (data)

✅ Real-Time Example

Login API Response (Spring Security + JWT):

json
CopyEdit
{
"token": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9..."
}
Subsequent request:

http
CopyEdit
GET /api/user/details
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...

✅ JWT Integration in Spring Boot – Code Overview

1. Add Dependency (Maven):

xml
CopyEdit
<dependency>
<groupId>[Link]</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>

2. Generate Token:

java
CopyEdit
String token = [Link]()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date([Link]() + 1000 * 60 *
60)) // 1 hour
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
3. Validate Token:

java
CopyEdit
Claims claims = [Link]()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();

String username = [Link]();

🔐 Summary

Feature JWT (JSON Web Token)

Used For Stateless Authentication in REST APIs


Contains Header, Payload (claims), Signature
Advantage No session, scalable, secure
Spring Use Case Token-based login authentication

==================================================

4) What is CORS Origin ?


✅ What is CORS (Cross-Origin Resource Sharing)?

CORS (Cross-Origin Resource Sharing) is a security feature


implemented by browsers that restricts web applications from
making HTTP requests to a different domain (origin) than the one
from which the web page was loaded.
What is an Origin?

An origin is defined by the scheme (protocol), domain (host), and


port.

Example:

• Page loaded from: [Link]


• API hosted at: [Link]

These are different origins, so CORS is required to access the API


from the web page.

🔒 Why is CORS Needed?

To protect users from malicious scripts making unauthorized requests


from a browser to another domain (cross-site requests). Without
CORS, modern browsers block these requests by default.

How to Handle CORS in Spring Boot

You can enable CORS in 3 ways:

✅ 1. Using @CrossOrigin Annotation

java
CopyEdit
@RestController
@CrossOrigin(origins = "[Link]
public class EmployeeController {

@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return [Link]();
}
}

✅ 2. Global CORS Configuration

java
CopyEdit
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
[Link]("/**")
.allowedOrigins("[Link]
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*");
}
}

✅ 3. CORS with Spring Security (if enabled)

java
CopyEdit
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws
Exception {
http
.cors()
.and()
.csrf().disable();
return [Link]();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
[Link]("[Link]
[Link]("*");
[Link]("*");

UrlBasedCorsConfigurationSource source = new


UrlBasedCorsConfigurationSource();
[Link]("/**", config);
return source;
}
}

🌐 Real-Time Example

Your frontend app is on:

arduino
CopyEdit
[Link] (React/Angular)

Your Spring Boot backend is on:

arduino
CopyEdit
[Link]

Now, to allow the frontend to talk to the backend, you must enable
CORS on the backend or else you'll get this browser error:

pgsql
CopyEdit
Access to fetch at '[Link] from origin
'[Link] has been blocked by CORS policy
🔍 Summary

Term Meaning

CORS Cross-Origin Resource Sharing


Why Needed Prevents unauthorized cross-domain requests
Enable via @CrossOrigin, WebConfig, or
In Spring
SecurityConfig
Frontend and backend run on different
Real Use
domains/ports

5) What is CSRF attack ?


What is CSRF (Cross-Site Request Forgery) Attack?

CSRF (Cross-Site Request Forgery) is a type of malicious exploit


where unauthorized commands are transmitted from a trusted user’s
browser to a web application in which they are authenticated.

How Does CSRF Work?

1. User logs in to a trusted website (e.g., banking site).


2. The site stores the session cookie in the browser.
3. While logged in, the user visits a malicious site.
4. The malicious site silently sends a request to the trusted site
(using user's session).
5. The server thinks the request is legit (since the session is valid)
and executes it.

Example Attack:
html
CopyEdit
<img src="[Link] />

If the user is already logged into [Link], this request might succeed
without their knowledge.

Real-Life Analogy

Imagine you left your email open on your computer. A friend comes
and sends a mail pretending to be you. The system has no idea you
didn't send it — because the session was active. That’s CSRF.

💡 How to Prevent CSRF in Spring Boot

✅ 1. Enable CSRF Protection (enabled by default in Spring


Security):

java
CopyEdit
[Link]().enable(); // default

Spring automatically adds a CSRF token to forms and expects it with


each state-changing request (POST, PUT, DELETE).

✅ 2. CSRF Token Example in HTML Form

html
CopyEdit
<form method="post" action="/transfer">
<input type="hidden" name="_csrf" value="${_csrf.token}">
<button type="submit">Transfer</button>
</form>
Spring injects the token value into the form using Thymeleaf, JSP,
etc.

✅ 3. Disable CSRF (for APIs using JWT or stateless auth)

java
CopyEdit
[Link]().disable(); // Not recommended for web forms

🚧 When to Disable CSRF

• If you're building REST APIs and using stateless


authentication like JWT.
• If there is no session and the client is sending Authorization
headers instead.

🔐 Summary

Feature Description

Forces authenticated users to


CSRF
unknowingly submit requests
Money transfer, password change, or
Impact
delete actions
CSRF tokens, SameSite cookies, custom
Defense
headers
Spring Default CSRF protection is enabled by default
6) Which tool you have used to consume REST
APIs?
To consume REST APIs, here are commonly used tools and
technologies depending on the context (Java/Spring Boot or
frontend):

✅ In Spring Boot (Java Backend):

1. RestTemplate (Traditional but still widely used)

java
CopyEdit
RestTemplate restTemplate = new RestTemplate();
String result =
[Link]("[Link]
[Link]);

2. WebClient (Preferred in modern Spring Boot, non-


blocking/reactive)

java
CopyEdit
WebClient webClient = [Link]();
String response = [Link]()
.uri("[Link]
.retrieve()
.bodyToMono([Link])
.block();

🔹 When to use WebClient over RestTemplate?

• WebClient is used for reactive applications.


• RestTemplate is blocking; WebClient is non-blocking.
✅ In Frontend (JavaScript/Angular/React):

1. Postman (for testing and consuming APIs manually)

2. Fetch API (Native JS)

javascript
CopyEdit
fetch('[Link]
.then(response => [Link]())
.then(data => [Link](data));

3. Axios (Popular JS library)

javascript
CopyEdit
[Link]('[Link]
.then(response => [Link]([Link]));

✅ Real-time Use Case Example:

In a Spring Boot microservice, suppose OrderService needs to call


CustomerService:

java
CopyEdit
@RestTemplate restTemplate = new RestTemplate();
Customer customer = [Link](
"[Link] + customerId,
[Link]);

Or using WebClient (recommended for microservices):

java
CopyEdit
Customer customer = [Link]()
.get()
.uri("[Link] customerId)
.retrieve()
.bodyToMono([Link])
.block();

==================================================
7) Can we use GET HTTP Request to send data to
server ?
Yes, you can send data to the server using a GET HTTP request, but
it has limitations and is generally not recommended for sensitive or
large data.

✅ When can you use GET to send data?

• When sending non-sensitive, small data (like query


parameters).
• Example: Search forms, filters, pagination.

📌 Example:

http
CopyEdit
GET /search?query=springboot&page=2 HTTP/1.1
Host: [Link]
In Spring Boot:

java
CopyEdit
@GetMapping("/search")
public String search(@RequestParam String query, @RequestParam
int page) {
return "Searching for: " + query + " on page " + page;
}

❌ Why not use GET for sending data?

Reason Explanation

Data is exposed in the URL, can be


Not secure
logged or bookmarked
Browsers/servers have limits on URL
Size limit
length (~2048 chars)
GET should not change server state
Idempotent
(no creation or update)
GET requests are often cached by
Caching issues
browsers/proxies

✅ Preferred method for sending data:

• Use POST for submitting form data, login credentials, JSON


body, or anything that modifies state or is sensitive.
🔐 Real-time Example:

• ❌ GET /login?username=john&password=1234 → Bad


practice
• ✅ POST /login with JSON body { "username": "john",
"password": "1234" }

==================================================
8) How you have implemented spring security in
your for API authorization ?

To implement Spring Security for API authorization in my project,


I followed a JWT (JSON Web Token)-based stateless
authentication approach. Here's a step-by-step explanation along
with real code and a real-world example:

✅ 1. Add Spring Security and JWT Dependencies


xml
CopyEdit
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
✅ 2. Create JWT Utility Class
java
CopyEdit
@Component
public class JwtUtil {

private String SECRET_KEY = "my_secret";

public String generateToken(UserDetails userDetails) {


return [Link]()
.setSubject([Link]())
.setIssuedAt(new Date())
.setExpiration(new Date([Link]() +
1000 * 60 * 60)) // 1 hour
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}

public String extractUsername(String token) {


return [Link]().setSigningKey(SECRET_KEY)
.parseClaimsJws(token).getBody().getSubject();
}

public Boolean validateToken(String token, UserDetails


userDetails) {
return
extractUsername(token).equals([Link]());
}
}

✅ 3. Create JWT Filter


java
CopyEdit
public class JwtFilter extends OncePerRequestFilter {

@Autowired
private JwtUtil jwtUtil;

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
String authHeader = [Link]("Authorization");

if (authHeader != null && [Link]("Bearer ")) {


String token = [Link](7);
String username = [Link](token);

if (username != null &&


[Link]().getAuthentication() == null) {
UserDetails userDetails =
[Link](username);
if ([Link](token, userDetails)) {
UsernamePasswordAuthenticationToken authToken =
new
UsernamePasswordAuthenticationToken(userDetails, null,
[Link]());

[Link](new
WebAuthenticationDetailsSource().buildDetails(request));

[Link]().setAuthentication(authToken);
}
}
}

[Link](request, response);
}
}
✅ 4. Configure Spring Security
java
CopyEdit
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtFilter jwtFilter;

@Autowired
private UserDetailsService myUserDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
[Link](myUserDetailsService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
[Link]().disable()
.authorizeRequests()
.antMatchers("/authenticate", "/public/**").permitAll()
.anyRequest().authenticated()
.and()

.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.
STATELESS);

[Link](jwtFilter,
[Link]);
}

@Bean
public AuthenticationManager authenticationManagerBean()
throws Exception {
return [Link]();
}
}

✅ 5. Create Authentication Endpoint


java
CopyEdit
@RestController
public class AuthController {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtUtil jwtUtil;

@Autowired
private UserDetailsService userDetailsService;

@PostMapping("/authenticate")
public ResponseEntity<?> generateToken(@RequestBody
AuthRequest authRequest) throws Exception {
try {
[Link](
new
UsernamePasswordAuthenticationToken([Link](),
[Link]())
);
} catch (Exception e) {
throw new Exception("Invalid Credentials");
}

final UserDetails userDetails =


[Link]([Link]()
);
final String token = [Link](userDetails);

return [Link](new AuthResponse(token));


}
}

✅ Real-time Use Case Example:

I worked on a RESTful microservice where:

• Frontend ([Link]) sends login credentials to /authenticate.


• Backend returns a JWT token.
• Token is stored in localStorage and added to Authorization:
Bearer <token> for each API call.
• APIs like /employees, /projects were protected and only
accessible with valid tokens.

🔒 Why JWT for API Authorization?

• Stateless (no server session needed)


• Secure (signed with secret key)
• Scalable for distributed systems
• Ideal for Microservices and SPA (Single Page Apps)

==================================================
9) What are the HTTP Methods ?

Here's a concise explanation of the most commonly used HTTP


methods in RESTful APIs, including examples and real-time use
cases for each:

✅ 1. GET

• Purpose: Retrieve data from the server.


• Safe and idempotent (does not change data).
• Example:

http
CopyEdit
GET /api/employees

• Spring Boot Example:

java
CopyEdit
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return [Link]();
}

• Real-time Use Case: Fetch all employees to show in a


dashboard.

✅ 2. POST

• Purpose: Create a new resource on the server.


• Not idempotent.
• Example:
http
CopyEdit
POST /api/employees
Body: { "name": "John", "salary": 50000 }

• Spring Boot Example:

java
CopyEdit
@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee
emp) {
return [Link](emp);
}

• Real-time Use Case: Register a new user or add a new product.

✅ 3. PUT

• Purpose: Update an entire existing resource.


• Idempotent.
• Example:

http
CopyEdit
PUT /api/employees/1
Body: { "id": 1, "name": "John", "salary": 60000 }

• Spring Boot Example:

java
CopyEdit
@PutMapping("/employees/{id}")
public Employee updateEmployee(@PathVariable int id,
@RequestBody Employee emp) {
[Link](id);
return [Link](emp);
}

• Real-time Use Case: Update full user profile details.

✅ 4. DELETE

• Purpose: Delete a resource.


• Idempotent.
• Example:

http
CopyEdit
DELETE /api/employees/1

• Spring Boot Example:

java
CopyEdit
@DeleteMapping("/employees/{id}")
public ResponseEntity<?> deleteEmployee(@PathVariable int
id) {
[Link](id);
return [Link]().build();
}

• Real-time Use Case: Deleting an employee or record.

✅ 5. PATCH

• Purpose: Partially update a resource.


• Not necessarily idempotent.
• Example:

http
CopyEdit
PATCH /api/employees/1
Body: { "salary": 70000 }

• Spring Boot Example (custom implementation needed):

java
CopyEdit
@PatchMapping("/employees/{id}")
public Employee updatePartial(@PathVariable int id,
@RequestBody Map<String, Object> updates) {
return [Link](id, updates);
}

• Real-time Use Case: Update only email or salary without


changing other fields.

✅ 6. OPTIONS

• Purpose: Check what HTTP methods are supported for a


resource.
• Used mainly in CORS preflight requests.
• Example:

http
CopyEdit
OPTIONS /api/employees

• Spring Boot: Handled automatically by Spring for CORS.


🔄 Summary Table:

Affects
Method Use Case Idempotent
Data
GET Read data ✅ Yes ❌ No
POST Create new data ❌ No ✅ Yes
PUT Update full data ✅ Yes ✅ Yes
DELETE Delete data ✅ Yes ✅ Yes
PATCH Partial update ❌ No ✅ Yes
Preflight/allowed
OPTIONS ✅ Yes ❌ No
methods

==================================================
10) What Are Idempotent HTTP Methods ?
✅ What Are Idempotent HTTP Methods?

Idempotent HTTP methods are those that can be called multiple


times without changing the result beyond the initial application.

In simple words: Calling the same request 1 time or 100 times will
have the same effect on the server.
🔁 List of Idempotent Methods:

HTTP
Idempotent Description
Method
Retrieves data. Does not change
GET ✅ Yes
anything.
Updates resource. Repeating the
PUT ✅ Yes
same update gives the same result.
Deletes resource. Deleting again has
DELETE ✅ Yes
no further effect.
Like GET but without response
HEAD ✅ Yes
body.
Checks supported methods for a
OPTIONS ✅ Yes
resource.

❌ Non-idempotent Methods:

HTTP
Idempotent Description
Method
Creates new resource each time — result
POST ❌ No
changes on each call.
Partially updates — multiple calls may lead
PATCH ❌ No
to different data states.

🔧 Real-time Example (DELETE):

http
CopyEdit
DELETE /api/users/10

• 1st call: Deletes user with ID 10.


• 2nd call: User already deleted. No change, still successful (204
No Content or 404).
• ✅ Hence, DELETE is idempotent.
==================================================
11) What Are Non-Idempotent HTTP
Methods?

❌ What Are Non-Idempotent HTTP Methods?

Non-idempotent methods are HTTP methods where making the


same request multiple times causes different effects on the server.

In simple terms: Each request modifies the server state — so


repeating it changes something every time.

🔁 List of Non-Idempotent Methods:

HTTP
Idempotent Description
Method
Used to create a new resource. Each call
POST ❌ No
creates a new entry.
Used to partially update a resource.
PATCH ❌ No Repeated calls may result in different states
based on current data.

🔧 Real-Time Examples:

✅ POST Example:

http
CopyEdit
POST /api/users
Body: { "name": "Abhijit", "email": "abhijit@[Link]" }

• 1st call: Creates a new user.


• 2nd call: Creates another new user with same data.
• 🎯 Effect changes each time — not idempotent.

✅ PATCH Example:

http
CopyEdit
PATCH /api/profile/101
Body: { "loginAttempts": 1 }

• Each call increments or modifies data based on current state.


• Result changes on every call — non-idempotent.

==================================================
12) What are the Safe and Unsafe HTTP
Methods?
✅ Safe vs. Unsafe HTTP Methods

In HTTP, methods are categorized as safe or unsafe based on whether


they modify server state.

🔒 Safe Methods

Definition:
Safe methods are read-only operations — they do not alter the
server's data.

HTTP
Safe Description
Method
GET ✅ Retrieves data from the server.
HEAD ✅ Same as GET, but only returns headers.
OPTIONS ✅ Returns supported methods and CORS info.
Echoes back the received request, used for
TRACE ✅
diagnostics.

✅ Real Example of a Safe Method:

http
CopyEdit
GET /api/products

• Fetches product list — does not change data.


• Can be safely repeated without any side effects.
Unsafe Methods

Definition:
Unsafe methods modify server state — like creating, updating, or
deleting resources.

HTTP Method Safe Description


POST ❌ Creates a new resource.
Updates or replaces an existing
PUT ❌
resource.
DELETE ❌ Deletes a resource.
PATCH ❌ Partially updates a resource.

❌ Real Example of an Unsafe Method:

http
CopyEdit
DELETE /api/user/101

• Deletes a user — modifies server state.


• Repeating it might cause an error or different result.

🔄 Summary

Property Safe Methods Unsafe Methods

Affects Data? ❌ No ✅ Yes


Depends (some may be
Repeatable? ✅ Yes (no side effects)
idempotent)
Example GET, HEAD, POST, PUT, DELETE,
Methods OPTIONS PATCH
=================================================
13) What are the HTTP Status Codes ?
HTTP status codes are three-digit numbers returned by a server to
indicate the result of a client's request. They are grouped by their first
digit:

✅ 1xx – Informational

Used during the request process (rarely used directly).

Code Meaning Description


Request received, client should
100 Continue
continue
Server switching protocols as
101 Switching Protocols
requested

✅ 2xx – Success

The request was successfully received, understood, and processed.

Code Meaning Description


200 OK Standard success response
Resource created (e.g., after
201 Created
POST)
Request accepted but not yet
202 Accepted
processed
204 No Content Success but no content to return

🔍 Example:

http
CopyEdit
HTTP/1.1 200 OK

3xx – Redirection

Further action is needed to complete the request.

Code Meaning Description

Resource moved permanently


301 Moved Permanently
to a new URI
302 Found Temporarily redirected
Resource not modified since
304 Not Modified
last request

❌ 4xx – Client Error

Request has incorrect syntax or cannot be fulfilled.

Code Meaning Description

400 Bad Request Malformed request syntax


401 Unauthorized Authentication required
Server refuses to authorize
403 Forbidden
the request
404 Not Found Requested resource not found
HTTP method not supported
405 Method Not Allowed
for this resource

🔍 Real-Time Example:

• Accessing a missing endpoint:


sql
CopyEdit
GET /api/book/999
--> HTTP/1.1 404 Not Found

❌ 5xx – Server Error

The server failed to fulfill a valid request.

Code Meaning Description

500 Internal Server Error Generic server error


Invalid response from
502 Bad Gateway
upstream server
Server is overloaded or
503 Service Unavailable
down
Server timed out
504 Gateway Timeout waiting for another
service

✅ Summary Table

Category Description Examples

1xx Informational 100, 101


2xx Success 200, 201, 204
3xx Redirection 301, 302, 304
4xx Client Error 400, 401, 403, 404
5xx Server Error 500, 502, 503, 504
14) What are the best practices to develop
RESTFUL web services ?

Here are best practices to follow when developing RESTful Web


Services that are clean, scalable, and maintainable:

✅ 1. Use Proper HTTP Methods


Operation HTTP Method
Create POST
Read GET
Update PUT or PATCH
Delete DELETE

🔍 Example:

http
CopyEdit
GET /api/employees
POST /api/employees
PUT /api/employees/101
DELETE /api/employees/101

✅ 2. Use Meaningful Resource URIs (Nouns, not Verbs)

❌ GET /getAllEmployees
✅ GET /employees

Use plural nouns for resources and sub-resources if needed:

http
CopyEdit
GET /departments/5/employees

✅ 3. Use HTTP Status Codes Properly


Code Meaning
200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
404 Not Found
500 Internal Server Error

✅ 4. Use Versioning in API

URL versioning is the most common:

http
CopyEdit
GET /api/v1/employees

Other methods: Header versioning, Media Type versioning.

✅ 5. Support Filtering, Sorting, and Pagination

🔍 Example:

http
CopyEdit
GET /employees?department=IT&sort=name&page=2&size=10
✅ 6. Return Consistent and Standardized Responses

Use a wrapper object with:

• status
• message
• data
• timestamp

json
CopyEdit
{
"status": "success",
"data": {
"id": 1,
"name": "John Doe"
},
"timestamp": "2025-07-31T[Link]Z"
}

✅ 7. Use HATEOAS (Hypermedia as the Engine of Application


State)

Enhance REST responses with links for navigation.

json
CopyEdit
{
"id": 101,
"name": "Alice",
"_links": {
"self": "/employees/101",
"department": "/departments/2"
}
}

✅ 8. Implement Global Exception Handling

Use @ControllerAdvice and @ExceptionHandler to manage errors


gracefully.

java
CopyEdit
@ExceptionHandler([Link])
public ResponseEntity<String>
handleNotFound(EmployeeNotFoundException ex) {
return new ResponseEntity<>([Link](),
HttpStatus.NOT_FOUND);
}

✅ 9. Secure APIs (Authentication & Authorization)

Use:

• Spring Security
• JWT Tokens
• OAuth2 for token-based authentication

Also, apply CORS policies where needed.

✅ 10. Documentation (Swagger/OpenAPI)

Use Swagger (springdoc-openapi or springfox) to generate API


documentation.

yaml
CopyEdit
GET /api/employees
Response: 200 OK
✅ Bonus Tips:

• Use DTOs to separate API models from entities.


• Validate inputs using @Valid, @NotNull, etc.
• Keep controller methods small and clean.
• Follow Separation of Concerns using layers: Controller →
Service → Repository.

==================================================

You might also like