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

Java REST API Basics

A REST API is a set of web addresses a program can use to ask for or change information, like a menu at a restaurant. Each address does a specific job and often returns JSON.

What is a REST API?

REST (Representational State Transfer) is an architectural style for networked applications that maps operations onto standard HTTP methods -- GET to read, POST to create, PUT to replace, DELETE to remove -- applied to named resources rather than custom action verbs. Following these conventions is what makes an API predictable to other developers without extra documentation.

Example: 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 use clear, resource-oriented URL paths like /users or /products rather than verb-based paths like /getUsers. You map incoming requests to these paths inside your application's routing layer, which is what decides which handler code runs for a given method-and-path combination.

Example: 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 is the de facto standard format REST APIs use to exchange data because it's compact, human-readable, and natively supported by JavaScript. In your controllers you should explicitly set the Content-Type response header to 'application/json' so clients know how to parse the body correctly.

Example: 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

You can accept extra, optional parameters through the request URL using query parameters, which are appended after a '?' and separated by '&' (for example ?page=2&limit=10). These are the natural place for filtering, pagination, or sorting options that aren't part of the resource's identity.

Example: 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

By combining an in-memory list as fake data, basic routing, and hand-built JSON strings, you can mock out a complete REST controller quickly to prototype and test an API's shape before wiring up a real database behind it.

Example: 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. #}
Common Mistakes
  1. Using verbs in the URL, like /getUsers, instead of a noun such as /users and letting the HTTP method (GET, POST) say the action.
  2. Returning status 200 for errors, when a missing item should be 404 and bad input 400.
  3. Using GET to change data, when GET should only read; use POST, PUT or DELETE.
Chapter Summary
  • Networking basics explain how programs communicate across a network.
  • Socket programming and the HTTP client allow programs to send and receive data.
  • REST API basics show how services exchange data over HTTP.
🔒

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.