REST stands for Representational State Transfer.
Architectural style for designing web services.
REST services are stateless, which means that they do not maintain any state between requests. This makes them scalable and reliable.
For us they are mainly interfaces for information retrieval.
Accessing REST¶
REST services are based on the HTTP protocol, and they use a set of well-defined verbs to manipulate resources.
Some are open and free, some need an API key (free or subscription)
The four main verbs in REST are:
GET: Retrieve a resource.
POST: Create a resource.
PUT: Update a resource.
DELETE: Delete a resource.
Retrieving data (GET)¶
A simple example without an API key (Strømpris API):
import requests
# Power prices in the NO1 zone on a particular date
url = "https://www.hvakosterstrommen.no/api/v1/prices/2025/09-29_NO1.json"
response = requests.get(url, verify=False) # Disable SSL verification for testing purposes
print(response.json())# Write JSON to file for viewing
import json
with open('downloads/power_price.json', 'w') as f:
json.dump(response.json(), f, indent=4)Creating data (POST)¶
For this example we assume there is an API server running locally.
We rely on the Flask framework (see flask_API.py) in the current folder.
Simple POST, GET, “UPDATE”, DELETE
Running a Flask instance from the terminal can be done similar to this:
conda activate tf_M1
python /Users/kristian/Documents/GitHub/IND320/D2Dbook/3_Data_sources/3_APIs/flask_API.py# POST data (stored locally in a dictionary)
id = 'test'
data = {'key': 'value'}
response = requests.post('http://localhost:8000/api/post/{}'.format(id), json=data)
print(response.json())# GET data
id = 'test'
response = requests.get('http://localhost:8000/api/get/{}'.format(id))
print(response.json())
# You can also test this in a browser since this is an HTTP based (and we use no passwords here).Change data (UPDATE)¶
This command can mostly be exchanged with POST.
The Flask framework does not have a separate UPDATE (see implementation in flask_API.py).
# UPDATE data
id = 'test'
data = {'key': 'new value'}
response = requests.post('http://localhost:8000/api/update/{}'.format(id), json=data)
print(response.json())Remove data (DELETE)¶
Let’s remove some data and try to read it again.
# DELETE data
id = 'test'
response = requests.delete('http://localhost:8000/api/delete/{}'.format(id))
print(response.json())# GET data again
id = 'test'
response = requests.get('http://localhost:8000/api/get/{}'.format(id))
print(response.json())Exercise¶
Look at flask_API.py.
Add “try-except” to GET to return an empty JSON when an ‘id’ does not exist.
Are there other potential sources of error here?