/*--- 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 for a reply with any // status code. 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: a request that gets // no reply throws an HTTPError. var unreachable = null; try { http.request({ url: "https://unknown.example.org/" }); } catch (e) { unreachable = e.name + ": " + e.message; } sendJSONResp({ weather: weather, logStatus: res.status, logBody: JSON.parse(res.body), unreachable: unreachable });