🚀 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
@RestController and @RequestMapping in Spring Boot
More Relevant Posts
-
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
-
🚀 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
-
-
🚀 JsonApi4j 1.6.1 is out — and there's a new home for it too! 👉 https://api4.pro/ The headline this time isn't a single feature — it's a refreshed api4.pro: a new landing page, restructured docs with a sidebar navigation, and a contact page. What's new on the site: → Splash landing page with feature highlights and a quick-start code snippet → Docs reorganized into 5 clear sections: Introduction, Getting Started, Framework Internals, Plugins, Advanced → Contact page for questions, feedback, and collaboration A quick recap of what's been added since my previous post about the 1.5.0 release. Also shipped since then: 🔧 Spec compliance — Added the missing POST / DELETE operations for To-Many relationships. Before, only full replacement (PATCH) was supported; now you can add or remove specific relationship members per the JSON:API spec. 📋 Startup state report & integrity checks — At boot, the framework prints a human-readable summary of registered resources, relationships, operations, and plugins, alongside misconfiguration warnings from new cross-checks across the Domain and Operations registries. Catch issues before the first request, and see exactly what's wired up. 📡 Custom response headers and status — Operations can now propagate arbitrary HTTP headers from downstream responses to the client, and override the response status code per-operation. 🪵 Logging strategy refactor — Most messages moved from INFO to DEBUG, with new log statements added across the processing pipeline. Cleaner production logs by default, richer detail when you need to debug. 🐛 Bugfixes — Plugin auto-configuration in the Spring module, and a property mix-up in the Quarkus module. --- JsonApi4j (https://lnkd.in/ezei7Usv) is an open-source framework for building APIs aligned with the JSON:API specification, with a strong focus on developer productivity and clean architecture. If you've been curious about the framework, this is a great time to take a look — the new docs make it much easier to get started. Feedback and contributions are always welcome! 🙌 #java #jsonapi #opensource #api #documentation
To view or add a comment, sign in
-
🚀 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
-
-
Day 63 of #90DaysOfCode Today I upgraded my Flask blog by adding a working contact form with email automation. This is an updated version of my previous Flask API-powered blog project. The application now allows users to send messages through the contact page, which are processed by the backend and sent via email using SMTP. What I added in this update • Contact form handling using Flask request methods • Email automation using Python smtplib • Secure credential management using environment variables • Integration with the existing Flask blog architecture Key concepts explored • Backend form processing • SMTP email automation • Environment variables with python-dotenv • Secure handling of sensitive credentials This upgrade helped me understand how real web applications process user input and trigger backend actions such as sending emails. GitHub Repository https://lnkd.in/gB-bnauz #Python #Flask #BackendDevelopment #WebDevelopment #SoftwareEngineering #90DaysOfCode
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
-
-
I've seen developers write 200 lines of config code. All of it could've been replaced with 3 annotations. That's the power of Spring Boot — if you know the right annotations. Most developers only scratch the surface. Here's the complete breakdown you actually need: BOOTSTRAP → @SpringBootApplication — main entry point, enables everything → @EnableAutoConfiguration — auto-configures beans from classpath → @ComponentScan — scans and registers Spring components LAYERED ARCHITECTURE → @Component — generic Spring-managed bean → @Service — business logic layer → @Repository — data access with exception translation → @RestController — builds REST APIs returning JSON/XML DEPENDENCY INJECTION → @Autowired — injects dependencies automatically → @Qualifier — resolves ambiguity between multiple beans → @Primary — marks default bean implementation WEB & REST APIs → @GetMapping / @PostMapping / @PutMapping / @DeleteMapping → @RequestBody — maps payload to Java object → @PathVariable — extracts values from URL → @RequestParam — reads query parameters DATABASE & JPA → @Entity — maps class to DB table → @Transactional — ensures atomic operations with rollback → @GeneratedValue — auto-generates primary key VALIDATION → @Valid — triggers validation on request → @NotNull / @NotBlank / @Email / @Pattern — enforce input rules EXCEPTION HANDLING → @ExceptionHandler — handles specific exceptions → @RestControllerAdvice — global error handling for REST APIs SECURITY → @EnableWebSecurity — enables Spring Security → @PreAuthorize — role/permission check before method execution ADVANCED → @Scheduled — runs cron jobs → @Async — executes methods asynchronously → @Cacheable / @CacheEvict — cache and invalidate results I've compiled all of this into a structured PDF carousel. Comment SPRING and I'll send it to your DMs. ♻ Repost if this helped someone on your network. Follow Narendra K. for more Java & Spring Boot content. #SpringBoot #Java #BackendDevelopment #JavaDeveloper #SpringFramework #SoftwareEngineering #WebDevelopment #Programming #InterviewPreparation
To view or add a comment, sign in
-
🚀 𝐟𝐢𝐧𝐝𝐁𝐲𝐈𝐝() 𝐯𝐬 𝐄𝐧𝐭𝐢𝐭𝐲𝐌𝐚𝐧𝐚𝐠𝐞𝐫.𝐟𝐢𝐧𝐝() — 𝐒𝐚𝐦𝐞 𝐆𝐨𝐚𝐥, 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐭 𝐌𝐢𝐧𝐝𝐬𝐞𝐭 Fetching an entity by ID sounds trivial… But in JPA, how you do it actually reflects your level of abstraction and control. Two approaches. Two philosophies. 🔹 𝗳𝗶𝗻𝗱𝗕𝘆𝗜𝗱() — 𝗧𝗵𝗲 𝗦𝗽𝗿𝗶𝗻𝗴 𝗗𝗮𝘁𝗮 𝗪𝗮𝘆 Most of the time, this is what you’ll use: 𝐎𝐩𝐭𝐢𝐨𝐧𝐚𝐥<𝐔𝐬𝐞𝐫> 𝐮𝐬𝐞𝐫 = 𝐮𝐬𝐞𝐫𝐑𝐞𝐩𝐨𝐬𝐢𝐭𝐨𝐫𝐲.𝐟𝐢𝐧𝐝𝐁𝐲𝐈𝐝(𝐢𝐝); ✔ Clean and expressive. ✔ Returns Optional → safer null handling. ✔ Fits perfectly in service/business layers. ✔ Reduces boilerplate. ✔ Designed for productivity. 👉 This is about developer experience and clean code. 🔹 𝗘𝗻𝘁𝗶𝘁𝘆𝗠𝗮𝗻𝗮𝗴𝗲𝗿.𝗳𝗶𝗻𝗱() — 𝗧𝗵𝗲 𝗝𝗣𝗔 𝗖𝗼𝗿𝗲 𝗪𝗮𝘆 Closer to the metal: 𝐔𝐬𝐞𝐫 𝐮𝐬𝐞𝐫 = 𝐞𝐧𝐭𝐢𝐭𝐲𝐌𝐚𝐧𝐚𝐠𝐞𝐫.𝐟𝐢𝐧𝐝(𝐔𝐬𝐞𝐫.𝐜𝐥𝐚𝐬𝐬, 𝐢𝐝); ✔ Native JPA API. ✔ Returns null if not found. ✔ Uses first-level cache before hitting DB. ✔ More control over persistence context. ✔ Ideal for custom or advanced use cases. 👉 This is about control and deeper understanding. 💡 𝗪𝗵𝗮𝘁 𝗜’𝘃𝗲 𝗹𝗲𝗮𝗿𝗻𝗲𝗱: Use findById() in 90% of cases. Reach for EntityManager when you need fine-grained control. Understanding both helps you debug and optimize better. Because at the end of the day… good backend development is not just about making it work, it’s about choosing the right level of abstraction. #SpringBoot #Java #JPA #Hibernate #BackendDevelopment #CleanCode #SoftwareEngineering #BestPractices #CodingTips
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