APIs & HTTP
A web API answers HTTP requests with structured data, usually JSON.
| Method | Purpose | Status | Meaning | |
|---|---|---|---|---|
GET |
read | 2xx | success | |
POST |
create | 3xx | redirect | |
PUT/PATCH |
update | 4xx | your mistake (404, 401, 429) | |
DELETE |
delete | 5xx | server’s mistake |
The built-in HTTP client
Configuration:
POST with a body:
Warning
A 404 does not throw. Check response.statusCode() yourself.
JSON
Java has no JSON parser in the standard library. Use Jackson or Gson:
Full example
Manners
- respect rate limits — on 429, back off instead of retrying immediately
- always set timeouts
- keys go in environment variables:
System.getenv("API_TOKEN") - one
HttpClientper application, not per request
★ Exercises
- Call any public API; print the status code and the first 200 characters.
- Print all response headers (
response.headers().map()). - Fetch three URLs one after another and measure the total time — you will parallelise this in chapter 15.
- Retry up to three times with growing delays when you get a 429.
- Read a token from an environment variable and send it as an
Authorizationheader. What should happen if the variable is missing?