← Back to Advanced Java Course | Chapter 7: Networking & APIs | Lesson 4 of 4

Java REST API की मूल बातें

एक REST API web addresses का एक set है जिसका उपयोग कोई program जानकारी मांगने या बदलने के लिए कर सकता है, जैसे किसी restaurant का menu। हर address एक specific काम करता है और अक्सर JSON return करता है।

What is a REST API?

REST (Representational State Transfer) networked applications के लिए एक architectural style है जो operations को standard HTTP methods पर map करती है -- पढ़ने के लिए GET, बनाने के लिए POST, replace करने के लिए PUT, हटाने के लिए DELETE -- custom action verbs के बजाय नामित resources पर लागू करते हुए। इन conventions का पालन करना ही किसी API को बिना अतिरिक्त documentation के दूसरे developers के लिए predictable बनाता है।

उदाहरण: What is a REST API?

java
public class Main {
	public static void main(String[] args) {
		String[] methods = {"GET /users", "POST /users", "PUT /users/1", "DELETE /users/1"};
		for (String m : methods) System.out.println(m); // standard HTTP methods on named resources
	}
}

Designing REST Endpoints

REST endpoints /getUsers जैसे verb-based paths के बजाय /users या /products जैसे साफ़, resource-oriented URL paths उपयोग करते हैं। आप incoming requests को अपने application की routing layer के अंदर इन paths पर map करते हैं, जो तय करती है कि किसी दिए गए method-and-path combination के लिए कौन सा handler code चले।

उदाहरण: Designing REST Endpoints

java
public class Main {
	static String route(String path) {
		return switch (path) {
			case "/users" -> "UserListHandler"; // resource-oriented, not /getUsers
			case "/products" -> "ProductListHandler";
			default -> "NotFound";
		};
	}
	public static void main(String[] args) {
		System.out.println(route("/users"));
	}
}

Serving JSON Data

JSON वह de facto standard format है जिसका उपयोग REST APIs data exchange के लिए करते हैं क्योंकि यह compact, human-readable है, और natively JavaScript द्वारा supported है। आपके controllers में आपको explicitly Content-Type response header को 'application/json' सेट करना चाहिए ताकि clients को पता चले कि body को सही तरीके से कैसे parse करना है।

उदाहरण: Serving JSON Data

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare contentType and set it to "application/json"
		String contentType = "application/json";
		// Declare json and set it to "{/"id/":1,/"name/":/"Riya/"}"
		String json = "{\"id\":1,\"name\":\"Riya\"}";
		// Print a line to the console
		System.out.println("Content-Type: " + contentType);
		// Print a line to the console
		System.out.println(json);
	}
}

Query Parameters in REST

आप request URL के ज़रिए query parameters का उपयोग करके अतिरिक्त, optional parameters accept कर सकते हैं, जिन्हें '?' के बाद जोड़ा जाता है और '&' से अलग किया जाता है (उदाहरण के लिए ?page=2&limit=10)। ये filtering, pagination, या sorting options के लिए स्वाभाविक जगह हैं जो resource की identity का हिस्सा नहीं हैं।

उदाहरण: Query Parameters in REST

java
public class Main {
	public static void main(String[] args) {
		String url = "/products?page=2&limit=10"; // filtering/pagination via query params
		String query = url.substring(url.indexOf('?') + 1);
		System.out.println(query);
	}
}

Mock REST Controller

fake data के रूप में एक in-memory list, basic routing, और हाथ से बनाई JSON strings को combine करके, आप किसी असली database wire करने से पहले किसी API की shape prototype और test करने के लिए जल्दी से एक पूरा REST controller mock कर सकते हैं।

उदाहरण: Mock REST Controller

java
import java.util.*;
public class Main {
	public static void main(String[] args) {
		List<String> users = new ArrayList<>(List.of("Riya", "Aman")); // in-memory fake data
		String path = "/users";
		if (path.equals("/users")) {
			System.out.println("[\"" + String.join("\",\"", users) + "\"]");
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. URL में /users जैसे noun के बजाय /getUsers जैसे verbs उपयोग करना और action को HTTP method (GET, POST) से बताने देना।
  2. errors के लिए status 200 return करना, जबकि कोई गायब item 404 और गलत input 400 होना चाहिए।
  3. data बदलने के लिए GET का उपयोग करना, जबकि GET को सिर्फ पढ़ना चाहिए; POST, PUT या DELETE का उपयोग करें।
चैप्टर सारांश
  • Networking basics बताते हैं कि programs किसी network पर कैसे communicate करते हैं।
  • Socket programming और HTTP client programs को data भेजने और पाने देते हैं।
  • REST API basics दिखाते हैं कि services HTTP पर data कैसे exchange करती हैं।
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.