Fetch JSON with GET

The most fundamental recipe: issue a GET request and parse the JSON body the server returns. It is read-only and carries no request body.

Overview

The most fundamental recipe: issue a GET request and parse the JSON body the server returns. It is read-only and carries no request body.

In code

curl https://api.example.com/users/1 \
  -H 'Accept: application/json'
const res = await fetch('https://api.example.com/users/1', {
  headers: { Accept: 'application/json' }
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
console.log(data);
import requests

res = requests.get('https://api.example.com/users/1',
                   headers={'Accept': 'application/json'})
res.raise_for_status()
data = res.json()
print(data)

Details

Send `Accept: application/json` to tell the server which representation you want. Many APIs return JSON without it, but on servers that do content negotiation it guarantees you get JSON rather than, say, XML.

GET is safe and idempotent, so repeating the request never changes server state. That is exactly why browsers, proxies, and CDNs are free to cache the response.

Always check the status before parsing. `fetch` does not reject on 404 or 500, so you must inspect `res.ok` yourself; with `requests`, call `raise_for_status()` to turn 4xx/5xx into exceptions.

Related headers

Related status codes