🚀 DAY 17 — ResponseEntity & Exception Handling ✅ 1. CLEAR CONCEPT (VERY IMPORTANT) 🔹 ResponseEntity 👉 Used to return: Data Status code Headers 💡 Instead of just returning data, 👉 you return complete HTTP response 🔹 Example @GetMapping("/user") public ResponseEntity<String> getUser() { return ResponseEntity.ok("User found"); } 👉 Response: Body → "User found" Status → 200 OK ⚡ WHY USE ResponseEntity? ✔ Control status code ✔ Custom response ✔ Better API design 🔴 EXCEPTION HANDLING (VERY IMPORTANT) 👉 Handles errors in clean way ❌ Without Exception Handling 👉 App crashes or messy error ✅ With Exception Handling 👉 Clean error response 💻 EXAMPLE (IMPORTANT 🔥) @GetMapping("/user/{id}") public ResponseEntity<String> getUser(@PathVariable int id) { if (id == 0) { throw new RuntimeException("User not found"); } return ResponseEntity.ok("User found"); } ⚙️ GLOBAL EXCEPTION HANDLER @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<String> handleException(RuntimeException ex) { return ResponseEntity .status(404) .body(ex.getMessage()); } } 🎯 INTERVIEW QUESTIONS (MUST 🔥) ❓ What is ResponseEntity? 👉 Used to return full HTTP response ❓ Why use ResponseEntity? 👉 To control status + response ❓ What is Exception Handling? 👉 Handling errors gracefully ❓ What is @RestControllerAdvice? 👉 Global exception handler ❓ What is @ExceptionHandler? 👉 Handles specific exception ⚡ COMMON STATUS CODES Code Meaning 200 OK 201 Created 400 Bad Request 404 Not Found 500 Server Error 💡 BEST PRACTICES ✔ Always use ResponseEntity ✔ Handle exceptions globally ✔ Return proper status codes 🔄 FLOW (IMPORTANT) 👉 Client → API → Exception → Handler → Response 💡 FINAL UNDERSTANDING 👉 ResponseEntity = control response 👉 Exception Handling = control errors 💬 Do you return proper status codes in your APIs? Day 17 done ✅ #SpringBoot #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #Developers
Spring ResponseEntity and Exception Handling Best Practices
More Relevant Posts
-
🚀 DAY 15 — Build REST APIs (GET, POST, PUT, DELETE) ✅ 1. CLEAR CONCEPT (VERY IMPORTANT) 👉 API = way for client to communicate with server 👉 REST APIs use HTTP methods 🌐 HTTP METHODS (CORE 🔥) MethodUseGETFetch dataPOSTCreate dataPUTUpdate dataDELETEDelete data 💻 FULL EXAMPLE (VERY IMPORTANT) @RestController @RequestMapping("/users") public class UserController { // GET → fetch users @GetMapping public List<String> getUsers() { return List.of("Ashish", "Rahul"); } // POST → add user @PostMapping public String addUser(@RequestBody String name) { return "User " + name + " added"; } // PUT → update user @PutMapping("/{id}") public String updateUser(@PathVariable int id, @RequestBody String name) { return "User " + id + " updated to " + name; } // DELETE → delete user @DeleteMapping("/{id}") public String deleteUser(@PathVariable int id) { return "User " + id + " deleted"; } } 🔄 FLOW (IMPORTANT) 👉 Client (Postman / Browser) → Controller → Method executes → Response returns 📌 API EXAMPLES GET → /users POST → /users PUT → /users/1 DELETE → /users/1 🎯 INTERVIEW QUESTIONS (MUST 🔥) ❓ What is REST API? 👉 Communication between client and server using HTTP ❓ Difference: GET vs POST? 👉 GET → fetch data 👉 POST → create data ❓ Difference: PUT vs PATCH? 👉 PUT → full update 👉 PATCH → partial update ❓ What is @RequestBody? 👉 Takes data from client ❓ What is @PathVariable? 👉 Gets value from URL ⚡ BEST PRACTICES (IMPORTANT) ✔ Use proper HTTP methods ✔ Use meaningful URLs (/users) ✔ Return proper responses ✔ Keep controller clean 💡 FINAL UNDERSTANDING 👉 GET → Read 👉 POST → Create 👉 PUT → Update 👉 DELETE → Remove 💬 Did you test APIs using Postman? Day 15 done ✅ #SpringBoot #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #Developers
To view or add a comment, sign in
-
-
🚀 Understanding HTTP Status Codes in REST APIs While building APIs, one important thing is not just sending data… 👉 It’s also about sending the right response status. These are called HTTP Status Codes. They help the client understand what happened with the request. 🔹 Common Status Codes ✔ 200 – OK Request was successful Example: Data fetched successfully ✔ 201 – Created New resource created Example: User registered successfully ✔ 400 – Bad Request Invalid input from client Example: Missing or wrong data ✔ 404 – Not Found Requested resource not found Example: User ID does not exist ✔ 500 – Internal Server Error Something went wrong on the server 🔹 Example in Spring Boot @GetMapping("/users/{id}") public ResponseEntity<User> getUser(@PathVariable Long id) { User user = userService.findById(id); return ResponseEntity.ok(user); } If user is not found, we can return: return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); 💡 Why Status Codes are important ✔ Help frontend understand response ✔ Improve API communication ✔ Make APIs more professional ✔ Very common in interviews Understanding status codes helped me connect concepts like exception handling, validation, and API design. #Java #SpringBoot #BackendDevelopment #APIDesign #Learning
To view or add a comment, sign in
-
-
APIs started making sense to me when I stopped memorizing… and started understanding the flow 👇 At a basic level, an API is just a way for systems to communicate. But what actually happens when you hit an API? Let’s break it down: 1️⃣ Client sends a request Example: GET /users/1 2️⃣ Request reaches the server → Routed to the correct controller 3️⃣ Business logic runs → Service layer processes the request 4️⃣ Database interaction → Fetch / update data 5️⃣ Response is returned → Usually JSON So the real flow is: 👉 Client → Controller → Service → Database → Response What helped me most was understanding this: • APIs are not just endpoints • They are structured layers working together Also, things started clicking when I focused on: • HTTP methods (GET, POST, PUT, DELETE) • Status codes (200, 404, 500) • Request & response structure Still learning, but understanding this flow made backend development much clearer. If you're learning APIs, focus on the flow — not just the syntax. #BackendDevelopment #APIs #Java #SpringBoot #WebDevelopment #Developers #LearningInPublic
To view or add a comment, sign in
-
-
🚀 DAY 14 — @RestController & @RequestMapping (CORE API CONCEPT 🔥) ✅ 1. CLEAR CONCEPT (VERY IMPORTANT) 👉 @RestController = Used to create REST APIs 👉 It combines: @Controller @ResponseBody 💡 Means: 👉 Return data (JSON), not HTML 👉 @RequestMapping = Maps URL to method/class 💡 Means: 👉 Which URL → which method 🧠 SIMPLE UNDERSTANDING 👉 Client calls API → Controller handles it 💻 EXAMPLE (VERY IMPORTANT) @RestController @RequestMapping("/api") public class UserController { @RequestMapping("/hello") public String hello() { return "Hello World"; } } 👉 Output: http://localhost:8080/api/hello ⚡ SHORTCUT ANNOTATIONS (IMPORTANT 🔥) Instead of @RequestMapping, use: @GetMapping @PostMapping @PutMapping @DeleteMapping ✔ More readable ✔ Mostly used in real projects 🔄 FLOW (VERY IMPORTANT) 👉 Client → Controller → Method → Response 🎯 INTERVIEW QUESTIONS (MUST KNOW 🔥) ❓ What is @RestController? 👉 Used to create REST APIs (returns JSON data) ❓ Difference: @Controller vs @RestController? 👉 @Controller → returns view (HTML) 👉 @RestController → returns data (JSON) ❓ What is @RequestMapping? 👉 Maps URL to controller method ❓ Can we use @RequestMapping at class level? 👉 Yes (for base URL) ❓ Why use @GetMapping instead of @RequestMapping? 👉 Short, clean, specific to HTTP method 📂 REAL USE CASE 👉 /api/users → get users 👉 /api/users/add → add user 💡 FINAL UNDERSTANDING 👉 @RestController = API creator 👉 @RequestMapping = URL mapping 💬 Did you try your first API yet? Day 14 done ✅ #SpringBoot #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #Developers
To view or add a comment, sign in
-
-
Stop designing APIs like it's 2015. Most developers still make these 7 mistakes that silently kill performance, scalability, and developer experience. After 14 years of building distributed systems, here's what I've learned the hard way: 1. Returning entire objects when clients need 2 fields Use field filtering: GET /users?fields=name,email Your bandwidth bill will thank you. 2. No versioning strategy from Day 1 "We'll add it later" = breaking 50 clients at 2 AM. Start with /v1/ in your URL or use header-based versioning. 3. Using HTTP 200 for everything 200 with {"error": "not found"} is NOT okay. Use proper status codes: 201, 204, 400, 404, 429. 4. Ignoring pagination on list endpoints Returning 10,000 records in one response? Your database and your users are both crying. 5. Synchronous processing for long-running tasks Don't make clients wait 30 seconds. Return 202 Accepted + a polling URL or use WebSockets. 6. No rate limiting until the system crashes Rate limit from Day 1. Not after the incident postmortem. Use token bucket or sliding window algorithms. 7. Inconsistent naming conventions /getUsers, /fetch_orders, /retrieveProducts? Pick ONE style (camelCase or snake_case) and stick to it. Good API design is not about following REST rules perfectly. It's about making life easier for the developers consuming your API. Which of these mistakes have you seen (or made)? Drop your biggest API horror story below. Follow Kuldeep Singh for daily System Design & Java insights. #SystemDesign #APIDesign #Java #Microservices #SoftwareArchitecture #BackendDevelopment #SpringBoot #TechLeadership #Programming #WebDevelopment
To view or add a comment, sign in
-
REST API Basics Every Developer Should Know 👇 GET → Fetch data POST → Create data PUT → Update full data PATCH → Update partial data DELETE → Remove data 💡 Bonus: Use proper HTTP status codes: 200 ✅ 201 ✅ 400 ❌ 500 ❌ Clean API = Professional developer 🚀 👉 Follow for backend mastery #restapi #backend #java #springboot #developers #coding #webdevelopment #softwareengineer #tech #learning #trending
To view or add a comment, sign in
-
🚀 Day 6 — Core Spring Annotations (Must Know 🔥) Today I learned the most important Spring annotations 👉 These are used in almost every real project 💡 1. @Component 👉 Marks a class as Spring Bean @Component class User {} 💡 2. @Service 👉 Used for business logic layer @Service class UserService {} 💡 3. @Repository 👉 Used for database layer @Repository class UserRepository {} 💡 4. @Controller 👉 Handles web requests @Controller class UserController {} 💡 5. @Autowired 👉 Injects dependency automatically @Autowired UserService service; ⚡ Important Point: 👉 All above annotations need @ComponentScan 📌 Key Takeaways: @Component → generic bean @Service → business logic @Repository → DB layer @Controller → request handling @Autowired → dependency injection 💡 One line I learned: 👉 Annotations replaced XML configuration 💬 Which annotation confused you the most? Day 6 done ✅ #Spring #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #SpringBoot #Developers
To view or add a comment, sign in
-
-
𝗠𝗼𝘀𝘁 𝗦𝗽𝗿𝗶𝗻𝗴 𝗕𝗼𝗼𝘁 𝗽𝗿𝗼𝗷𝗲𝗰𝘁𝘀 𝗮𝗿𝗲𝗻'𝘁 𝗽𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻-𝗿𝗲𝗮𝗱𝘆. They have controllers. They have CRUD. But they are missing what actually matters. I built a Student Portal API not to tick boxes, but to deeply understand what separates a demo from a deployable system. Here is what that looked like in practice 𝗦𝘁𝗮𝘁𝗲𝗹𝗲𝘀𝘀 𝗔𝘂𝘁𝗵 𝘄𝗶𝘁𝗵 𝗝𝗪𝗧, 𝗻𝗼𝘁 𝘀𝗲𝘀𝘀𝗶𝗼𝗻𝘀 Built a custom JWT filter that intercepts every request before it hits business logic. No session state means horizontally scalable by design. 𝗥𝗲𝗮𝗹 𝗦𝗲𝗰𝘂𝗿𝗶𝘁𝘆, 𝗻𝗼𝘁 𝗰𝗵𝗲𝗰𝗸𝗯𝗼𝘅 𝘀𝗲𝗰𝘂𝗿𝗶𝘁𝘆 BCrypt for password hashing, never plain storage. Spring Security config that locks down endpoints with precision, not a blanket permit-all. 𝗗𝗧𝗢𝘀 𝗼𝘃𝗲𝗿 𝗘𝗻𝘁𝗶𝘁𝘆 𝗘𝘅𝗽𝗼𝘀𝘂𝗿𝗲 Your database schema is not your API contract. Separated entity models from response objects to prevent over-fetching, accidental field leaks, and tight coupling. 𝗣𝗮𝗴𝗶𝗻𝗮𝘁𝗶𝗼𝗻 𝗮𝗻𝗱 𝗦𝗼𝗿𝘁𝗶𝗻𝗴 𝗼𝗻 𝗹𝗮𝗿𝗴𝗲 𝗱𝗮𝘁𝗮𝘀𝗲𝘁𝘀 Most tutorials return everything. Production does not. Built proper paginated responses so the API holds up under real query loads. 𝗖𝗲𝗻𝘁𝗿𝗮𝗹𝗶𝘇𝗲𝗱 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 Predictable API behavior means consistent error contracts. One place to catch, format, and return meaningful error responses. 𝗕𝗶𝗴𝗴𝗲𝘀𝘁 𝗶𝗻𝘀𝗶𝗴𝗵𝘁 Authentication is not a login API. It is a request lifecycle problem. Every request must be verified, parsed, and authorized before business logic ever runs. That is what a JWT filter actually solves. 𝗧𝗲𝗰𝗵 𝗦𝘁𝗮𝗰𝗸 Java 17, Spring Boot, Spring Security, JWT, Hibernate, PostgreSQL 𝗖𝘂𝗿𝗿𝗲𝗻𝘁𝗹𝘆 𝗲𝘅𝘁𝗲𝗻𝗱𝗶𝗻𝗴 𝘄𝗶𝘁𝗵 Role-based access control Refresh token rotation Response caching layer If you are building backend projects, stop optimizing for happy paths. 𝗕𝘂𝗶𝗹𝗱 𝗳𝗼𝗿 𝗵𝗼𝘄 𝘀𝘆𝘀𝘁𝗲𝗺𝘀 𝗯𝗲𝗵𝗮𝘃𝗲 𝘂𝗻𝗱𝗲𝗿 𝗿𝗲𝗮𝗹 𝗰𝗼𝗻𝗱𝗶𝘁𝗶𝗼𝗻𝘀. That is what interviewers, code reviewers, and production will test you on. #SpringBoot #Java #BackendDevelopment #SpringSecurity #JWT #SoftwareEngineering #APIDevelopment
To view or add a comment, sign in
-
Spring Boot in Real Projects — Day 19 We already know how APIs return data. But what happens when your application grows and starts handling hundreds or even thousands of tasks daily whether from a single user or many users? For example: User1 → 50 tasks User2 → 120 tasks User3 → 300 tasks It's simple to fetch data for user-1 and next user-2 with 120 tasks gets heavy to fetch and for the next user-3 its hard to fetch and the API response may gets slow, to solve this Pagination & Sorting come in What is Pagination? Pagination is the process of dividing data into smaller chunks (pages) and fetching only the required portion instead of loading everything at once. What is Sorting? Sorting allows us to order data based on a specific field like createdAt, title, etc. Flow Client → Controller → Pageable → Repository → Database (applies LIMIT, OFFSET, ORDER BY) → Returns Page → Response to Client #SpringBoot #Java #BackendDevelopment #Pagination #APIDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
In production Spring Boot services, scattered try-catch blocks create inconsistent API behavior. A better approach is centralized handling: ```@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(new ErrorResponse("RESOURCE_NOT_FOUND", ex.getMessage())); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("VALIDATION_ERROR", "Invalid request payload")); } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleGeneric(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(new ErrorResponse("INTERNAL_ERROR", "Unexpected error occurred")); } }``` Benefits we observed: - Consistent contract for error payloads - Cleaner controllers/services - Accurate HTTP semantics (400, 404, 409, 500) - Better observability and incident response A strong error model is part of API design, not just exception handling. #SpringBoot #Java #Microservices #API #SoftwareEngineering #Backend
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development