| 12345678910111213141516171819202122232425262728293031 |
- /*---
- title: Call a web API
- group: Services
- summary: http.get and http.request answered by the rules in the HTTP window.
- setup: {"mocks":{"http":{"rules":[{"method":"GET","url":"https://api.example.com/weather?city=*","status":200,"headers":{"Content-Type":"application/json"},"body":"{\"city\": \"Hong Kong\", \"temp\": 27, \"sky\": \"cloudy\"}"},{"method":"POST","url":"https://api.example.com/log","status":201,"body":"{\"stored\": {{body}}}"}]}}}
- ---*/
- /*
- The playground has no network: open the HTTP window to change what each
- URL answers, add a delay, or make a request fail.
- */
- requirelib("http");
- // http.get returns the body as a string.
- var weather = JSON.parse(http.get("https://api.example.com/weather?city=Hong%20Kong"));
- // http.request returns status, headers and body, and does not throw.
- var res = http.request({
- url: "https://api.example.com/log",
- method: "POST",
- json: { user: USERNAME, temp: weather.temp }
- });
- // A URL no rule matches fails like an unreachable host.
- var down = http.request({ url: "https://unknown.example.org/" });
- sendJSONResp({
- weather: weather,
- logStatus: res.status,
- logBody: JSON.parse(res.body),
- unreachable: down.error
- });
|