REST
restapi1RestConcepts
- Path
- pkg12restapi/restapi1RestConcepts.java
- Package
- pkg12restapi
- Study order
- 1
- Run
- Single-file source launch
- Command
- java pkg12restapi/restapi1RestConcepts.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg12restapi;2 3/*4 * restapi1RestConcepts.java5 * -------------------------6 * REST fundamentals: the vocabulary of web APIs (no code to run, just the map).7 *8 * DEFINITION:9 * REST (REpresentational State Transfer) is an architectural style for APIs10 * over HTTP. Resources (nouns) are identified by URLs; HTTP methods (verbs)11 * act on them; representations (JSON/XML) carry their state.12 *13 * THE 6 REST CONSTRAINTS (brief):14 * 1. Client–Server — separate UI from data storage.15 * 2. Stateless — each request carries all context (no server session).16 * 3. Cacheable — responses say if/how they can be cached.17 * 4. Uniform Interface — consistent resource URLs + standard methods.18 * 5. Layered System — proxies/gateways are transparent.19 * 6. Code on Demand — (optional) server can ship executable code.20 */21public class restapi1RestConcepts {22 23 public static void main(String[] args) {24 System.out.println("HTTP methods (verbs) and their REST meaning:");25 print("GET", "read a resource (safe, idempotent)");26 print("POST", "create a new resource (not idempotent)");27 print("PUT", "replace a resource (idempotent)");28 print("PATCH", "partially update a resource");29 print("DELETE", "remove a resource (idempotent)");30 31 System.out.println("\nResource URL design (nouns, plural, hierarchical):");32 System.out.println(" GET /users -> list users");33 System.out.println(" GET /users/42 -> one user");34 System.out.println(" POST /users -> create user");35 System.out.println(" PUT /users/42 -> replace user 42");36 System.out.println(" DELETE /users/42 -> delete user 42");37 System.out.println(" GET /users/42/orders -> sub-resource");38 39 System.out.println("\nKey status codes:");40 status(200, "OK"); status(201, "Created");41 status(204, "No Content"); status(400, "Bad Request");42 status(401, "Unauthorized");status(403, "Forbidden");43 status(404, "Not Found"); status(409, "Conflict");44 status(422, "Unprocessable Entity"); status(500, "Internal Server Error");45 46 System.out.println("\nCommon headers:");47 System.out.println(" Content-Type: application/json (what the body IS)");48 System.out.println(" Accept: application/json (what the client WANTS)");49 System.out.println(" Authorization: Bearer <token> (who the client IS)");50 51 System.out.println("\nNext: restapi2 builds a server, restapi3 adds CRUD routing,");52 System.out.println("restapi4 handles JSON, restapi5 consumes it with HttpClient.");53 }54 55 static void print(String verb, String meaning) { System.out.printf(" %-7s %s%n", verb, meaning); }56 static void status(int code, String text) { System.out.printf(" %d %s%n", code, text); }57}