How do I get JSON from a REST API endpoint? [Python Code]
To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON. In this REST API GET example, we are making a GET request to the ReqBin echo REST API endpoint. The Content-Type: application/json response header indicates that the REST API server returned JSON. The Python code was automatically generated for the REST API GET example.
A REST API (Representative State Transfer) is a way of communicating two computers to each other over the Internet. The REST API defines a set of rules that developers should follow when creating an API.
1. Client-server architecture: the REST API client (website or mobile app) should be decoupled from the request processor and data storage (REST API server) so that each part can be developed, tested, and scaled individually. 2. Statelessness: every request to the REST API server must be made with all the required data, and no assumption should be made if the server has any data from previous REST API client requests (the server does not store the client context). 3. Layered: the REST API client does not need to know if it is communicating with a real server, proxy, or any other intermediary. These intermediate servers (proxies or load balancers) can provide additional scalability and security to the underlying REST API server. 4. Cacheable: each REST API response must be defined as cacheable or not.
REST API GET Example
To get data from the REST API server, you must send an HTTP GET request with an Accept: application/json request header. Below is an example of a REST API GET request to the ReqBin REST API endpoint.
REST API GET Request
GET /echo/get/json HTTP/1.1
In this REST API GET request example, the server informs the REST API client that it has returned JSON by sending Content-Type: application/json in response.
The server response to our test REST API GET request.
REST API Server Response
HTTP/1.1 200 OK