Skip to lesson content
Web Technologies › Level 27
LEVEL 27 · WEB APIs + REST

Web APIs and REST

Design predictable resource requests, representations and response outcomes.

☕ Java web📨 HTTP methods🧩 JSON contracts🧪 Lab + MCQs
01

Learning Objectives

Resources

Give collections and items clear identifiers.

Methods

Distinguish reads, creation, replacement and deletion.

Responses

Match status, headers and body to the outcome.

Contracts

Validate JSON and conditional changes deliberately.

02

An API Is an Application Contract

API boundary
Client

Constructs a request.

API handler

Validates and authorizes.

Application

Coordinates the operation.

Representation

Returns accepted public data.

03

REST Constraints and Practical HTTP APIs

Client/server

Separate presentation and application responsibilities.

Stateless request

Carry the needed interaction context.

Cache rules

State whether a response can be reused.

Uniform interface

Use resources and protocol semantics deliberately.

04

Collection and Item URLs

GET    /api/tasks      read collection
POST   /api/tasks      create a task
GET    /api/tasks/1    read one task
PUT    /api/tasks/1    replace existing task fields
DELETE /api/tasks/1    delete an existing task
05

Methods, Safety and Idempotency

MethodTask operationImportant distinction
GETRead collection/itemNo requested mutation
POSTCreate in collectionRepeated accepted request can create another item
PUTReplace existing title/completed fieldsFull accepted field set, not a partial patch
DELETERemove existing itemRepeated response may differ
06

JSON Syntax and Application Shape

{
  "title": "Review HTTP methods",
  "completed": false
}
07

Content-Type and Representation Expectations

POST /api/tasks
Content-Type: application/json

{"title":"Review HTTP","completed":false}

Expected accepted creation:
201 Created
Location: /api/tasks/3
Content-Type: application/json

The request text illustrates an HTTP contract; no request is sent when the lesson lab runs.

08

Status Codes, Location and Empty Bodies

200 / 201

Accepted result or created resource.

204

No response content to parse.

400 / 415

Invalid representation or media type.

428 / 412

Required condition absent or no longer matching.

The lab clears old previews on every error. A stale task card must not make a failed change look successful.

09

Validate Before Changing Application State

Mutation gate
Route/method

Choose a known operation.

Validate

Accept media type and data contract.

Condition

Check limits or current item version.

Apply

Change only accepted task state.

10

ETag and Conditional Updates

GET /api/tasks/1
→ 200, ETag: "task-1-v1"

PUT /api/tasks/1
If-Match: "task-1-v1"
Content-Type: application/json

{"title":"A changed title","completed":true}

GET again before editing with the new validator.
11

Caching and Validators Are Different Decisions

Validator

Identify a representation version.

Freshness

State when reuse is allowed.

Privacy

Protect user-specific response data.

Integration

Verify actual cache/proxy behavior.

The 428 response is not cacheable; this lab’s no-store policy also covers that outcome explicitly.

12

Browser Fetch and Response Parsing

async function readTasks() {
    const response = await fetch("/api/tasks");
    if (!response.ok) {
        throw new Error("Task read was not accepted");
    }
    const type = response.headers.get("Content-Type") || "";
    if (type.split(";")[0].trim().toLowerCase() !== "application/json") {
        throw new Error("Unexpected representation");
    }
    const data = await response.json();
    // Validate data shape before presenting task rows.
    return data;
}
13

CORS, Origins and Preflight

Separate permission boundaries
Browser origin

Applies script access rules.

CORS policy

Server declares allowed cross-origin access.

Authentication

Establishes caller identity.

Authorization

Checks the requested operation.

The local lab sends no requests or CORS preflights. Its behavior cannot prove Cloudflare/Render origin configuration.

14

Authentication, Authorization and Error Design

{
  "error": {
    "code": "stale_version",
    "message": "Read the task again before changing it."
  }
}

The next lesson develops Web Security. The task lab has no authentication and makes no claim of protecting real user data.

15

Pagination, Compatibility and Contract Tests

Bounded results

Specify order and pagination.

Compatibility

Make contract changes deliberate.

Retries

Distinguish repeatable effects from duplicate work.

Documentation

Verify examples against behavior.

Rejected input

No ID allocation or state mutation.

Accepted write

Controlled outcome and public representation.

Stale condition

Reject without overwriting current state.

Transport

Verify real headers/network independently.

16

Premium Visualizer — An API Resource Request

Follow an accepted task creation through routing, validation, state change, response and safe presentation. This approved five-stage player explains the request contract without sending HTTP.

API RESOURCE REQUEST TRACE
Step 1 of 5
STEP 01

Identify the resource operation

POST to the task collection requests creation.

POST /api/tasks

What is happening?

A collection write differs from item read/replacement/deletion.

17

Premium Interactive — A Local Task API Contract

Idle. Local JavaScript API model; no HTTP request sent.

Current mock resource state · versions are internal teaching data

Simulated request

No request yet.

Decision trace

No trace yet.

Response status and headers

No response yet.

Response body · displayed literally

No response body yet.

Safe outcome preview

No result yet.
18

Debugging — Inspect the First Rejection

Route/method

Compare exact path and Allow before assuming body failure.

Representation

Check media type, syntax, keys and value types.

Condition

Read the current tag instead of overwriting a changed task.

Empty body

A204 is complete without JSON content.

19

Interview Questions — Flip to Explain

QUESTION

Is every JSON endpoint fully RESTful?

Click or press Enter to explain
ANSWER

No. REST has architectural constraints beyond JSON and resource-looking paths; describe the actual API contract.

QUESTION

What does idempotency mean?

Click or press Enter to explain
ANSWER

Repeating the same request has the same intended effect; status and response body need not be identical.

QUESTION

Why can repeated accepted POST create duplicate work?

Click or press Enter to explain
ANSWER

POST does not provide a general idempotent creation guarantee; a separate enforced retry policy may be needed.

QUESTION

What does Content-Type describe?

Click or press Enter to explain
ANSWER

The representation in the message; Accept describes what response representations the client can receive.

QUESTION

Why return201 with Location after creation?

Click or press Enter to explain
ANSWER

It communicates creation and identifies the created resource in this contract.

QUESTION

Why should a204 not be parsed as JSON?

Click or press Enter to explain
ANSWER

It has no response content; the client must handle the completed empty outcome.

QUESTION

What does a stale If-Match check prevent in this model?

Click or press Enter to explain
ANSWER

It prevents replacing/deleting a task whose current version no longer matches the supplied condition.

QUESTION

Does CORS authenticate a caller?

Click or press Enter to explain
ANSWER

No. It controls browser cross-origin access; authentication and authorization remain separate backend checks.

20

MCQ Practice — Explain API Outcomes

PRACTICE

1. Which URL identifies the task collection?

PRACTICE

2. Which operation creates a task in this lab?

PRACTICE

3. What does idempotency describe?

PRACTICE

4. Which type is completed in an accepted task body?

PRACTICE

5. Which header identifies the created resource?

PRACTICE

6. What content does a204 deletion return?

PRACTICE

7. What does this lab return for unsupported methods?

PRACTICE

8. What happens on a well-formed stale If-Match?

PRACTICE

9. What happens when the required If-Match is absent?

PRACTICE

10. What does the successful normalized PUT do about a response validator?

PRACTICE

11. What does CORS provide?

PRACTICE

12. Does this local model verify real HTTP/CORS/concurrency?

21

Extra Practice — Follow a Resource Lifecycle

Read

GET collection:200, two tasks. GET /api/tasks/1:200 with quoted tag task-1-v1.

Create

POST collection with New task/false:201, Location /api/tasks/3, three stored items. Repeat: another item.

Replace

PUT item1 with changed fields and tagv1:200, version2 internally, no response ETag. GET again for tagv2.

Stale update

Repeat changed PUT with old tagv1:412 and unchanged current task.

Delete

DELETE item1 with current tag:204 and empty body. Repeat:404; no additional mutation.

Bad input

Try invalid JSON, completed as string, extra ID or text/plain on POST. Expect400/415 and no allocation.

Required condition

Empty If-Match on PUT/DELETE:428. Malformed tag:400. Valid tag for another version/item:412.

Literal text

Create title <Demo> & API. It remains text in JSON/preview. Reset restores original task state.

22

Quick Revision

Resource: Collection and item identifiers.
Method: Read/create/replace/delete contract.
JSON: Syntax and application shape differ.
Media type: Describe message representation.
Outcome: Status, headers and body agree.
204: Completed empty response.
Conditional write: Avoid overwriting stale versions.
Caching: Validator and reuse policy differ.
CORS: Browser access, not identity.
Integration: Verify actual transport/security separately.
23

Glossary — Flip to Learn

TERM

Web API

Click to see meaning
DEFINITION

Web API

An application interface accessed through web requests and responses.

TERM

Resource

Click to see meaning
DEFINITION

Resource

A concept identified and interacted with through the application protocol.

TERM

Representation

Click to see meaning
DEFINITION

Representation

A particular description of resource state, such as JSON.

TERM

REST

Click to see meaning
DEFINITION

REST

An architectural style with defined distributed-system constraints.

TERM

Safe method

Click to see meaning
DEFINITION

Safe method

A method whose requested semantics are read-only.

TERM

Idempotency

Click to see meaning
DEFINITION

Idempotency

The same intended effect when an identical request is repeated.

TERM

Content-Type

Click to see meaning
DEFINITION

Content-Type

Metadata describing the representation carried by a message.

TERM

ETag

Click to see meaning
DEFINITION

ETag

A validator identifying a representation version.

TERM

If-Match

Click to see meaning
DEFINITION

If-Match

A request condition requiring a matching current representation validator.

TERM

CORS

Click to see meaning
DEFINITION

CORS

A browser protocol for controlled cross-origin response access.

24

Final Challenge — Specify a Task API

25

Level 27 Complete?

Explain resource/method/representation distinctions, reproduce creation/replacement/deletion and stale preconditions, and handle204 without JSON parsing. Identify the actual transport/security checks the local lab cannot perform. Completion is a local study marker.