🚀 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
REST API Basics with GET, POST, PUT, DELETE in Java
More Relevant Posts
-
🚀 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
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
-
-
Day 28. I fixed the N+1 problem. Or at least… I thought I did. I had this: @Entity public class User { @OneToMany(mappedBy = "user", fetch = FetchType.LAZY) private List<Order> orders; } And I was careful. I wasn't using EAGER. I avoided obvious mistakes. Still… something felt off. The API was slow. Query count was high. That's when I checked the logs. And saw this: → 1 query to fetch users → N queries to fetch orders Again. Even after "fixing" it. Here's what was actually happening. I was mapping entities to DTOs like this: users.stream() .map(user -> new UserDTO( user.getId(), user.getName(), user.getOrders().size() // 👈 triggers lazy load per user )) .toList(); Looks harmless. But user.getOrders() → triggers lazy loading → inside a loop → causing N+1 again That's when it clicked. N+1 isn't just about fetch type. It's about when and where you access relationships. So I changed it. (see implementation below 👇) What I learned: → LAZY doesn't mean safe → DTO mapping can silently trigger queries → N+1 often hides in transformation layers The hard truth: → You think you fixed it → But it comes back in a different place Writing queries is easy. Controlling when data is accessed is what makes your backend scalable. Have you ever fixed N+1… and then seen it come back somewhere else? 👇 Drop your experience #SpringBoot #Java #Hibernate #BackendDevelopment #Performance #JavaDeveloper
To view or add a comment, sign in
-
-
Day 14. My API worked perfectly. Until it hit 100 users. I had this: List<Order> orders = orderRepository.findAll(); for (Order order : orders) { System.out.println(order.getUser().getName()); } Because of queries I didn’t even know existed. Looks clean. It’s not. Here’s what was actually happening: → 1 query to fetch all orders → 1 query per order to fetch the user → 100 orders = 101 queries hitting your database That’s the N+1 problem. And it hides in plain sight. Your code looks clean. Your database is suffering. And you probably have this in your codebase right now. The fix is simple: Fetch what you need. In one query. @Query("SELECT o FROM Order o JOIN FETCH o.user") List<Order> findAllWithUser(); One query. One JOIN. Everything loaded together. What actually changes: → Performance — 101 queries becomes 1 → Scalability — works at 100 rows, breaks at 100,000 → Visibility — you won’t notice until production The hard truth: → ORMs make it easy to write slow code → Lazy loading is convenient until it isn’t → You need to know what SQL your code is generating Writing code that works is easy. Writing code that doesn’t silently destroy your database is the real skill. Are you logging your SQL queries in development? If not — you should be. 👇 Drop it below #SpringBoot #Java #Hibernate #BackendDevelopment #JavaDeveloper
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
-
-
🚀 DAY 16 — @PathVariable, @RequestParam, @RequestBody ✅ 1. CLEAR CONCEPT (VERY IMPORTANT) 👉 These 3 are used to get data from client AnnotationFrom where data comes@PathVariableURL path@RequestParamQuery parameter@RequestBodyRequest body (JSON) 🧠 SIMPLE UNDERSTANDING 👉 3 ways client sends data: URL → /users/1 → PathVariable Query → /users?id=1 → RequestParam Body → JSON → RequestBody 💻 EXAMPLES (VERY IMPORTANT) 🔹 1. @PathVariable @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User id: " + id; } 👉 URL: /users/1 🔹 2. @RequestParam @GetMapping("/users") public String getUser(@RequestParam int id) { return "User id: " + id; } 👉 URL: /users?id=1 🔹 3. @RequestBody @PostMapping("/users") public String addUser(@RequestBody String name) { return "User " + name + " added"; } 👉 Body (JSON): { "name": "Ashish" } 🔄 FLOW (IMPORTANT) 👉 Client → sends data → Controller receives → Method executes 🎯 INTERVIEW QUESTIONS (MUST 🔥) ❓ Difference: @PathVariable vs @RequestParam? 👉 PathVariable → part of URL 👉 RequestParam → query parameter ❓ What is @RequestBody? 👉 Takes JSON data from client ❓ When to use @PathVariable? 👉 When ID is part of URL ❓ When to use @RequestParam? 👉 For optional/filter values ⚡ BEST PRACTICES ✔ Use PathVariable for IDs ✔ Use RequestParam for filters/search ✔ Use RequestBody for POST/PUT 💡 FINAL UNDERSTANDING 👉 Path → URL data 👉 Param → Query data 👉 Body → JSON data 💬 Which one confused you — Path or Param? Day 16 done ✅ #SpringBoot #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #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
-
💡 Using @Transactional in a GET API — Do You Really Need It? Most developers think @Transactional is only for INSERT/UPDATE/DELETE operations… but what about GET APIs? 🤔 Let’s break it down in the simplest way possible 👇 ⸻ 🔹 What does @Transactional do? It tells Spring: 👉 “Wrap this method in a database transaction.” That means: • All DB operations inside run safely • Either everything succeeds OR everything rolls back ⸻ 🔹 But GET API only reads data… why use it? Good question 👍 Even in read operations, @Transactional can be useful in some cases: ⸻ ✅ 1. To Avoid Lazy Loading Errors If you’re using JPA/Hibernate and fetching related data (like user.getOrders()), you might face: ❌ LazyInitializationException 👉 Why? Because the DB session is already closed. 💡 Solution: Using @Transactional keeps the session open while data is being fetched. ⸻ ✅ 2. To Ensure Consistent Data Imagine: • You are reading multiple tables • Data is changing at the same time Without transaction: 👉 You might get inconsistent results With @Transactional: 👉 You get a consistent snapshot of data ⸻ ✅ 3. For Better Performance (Read-Only Mode) You can write: @Transactional(readOnly = true) 👉 This tells the database: • “I’m only reading data, not modifying it” ⚡ Result: • Better performance • Less overhead ⸻ ⚠️ When NOT to use it? Don’t blindly add it to every GET API ❌ Avoid if: • Simple single-table fetch • No lazy loading • No complex logic 👉 Because transactions also add overhead ⸻ 🔥 Simple Rule to Remember: ✔ Complex read → Use @Transactional(readOnly = true) ❌ Simple read → Skip it ⸻ 🧠 Final Thought @Transactional is not just for writing data — it’s about managing how you interact with the database safely and efficiently. ⸻ #Java #SpringBoot #BackendDevelopment #CodingTips #Developers #TechSimplified
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
-
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 related topics
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