08-http-mock.agi 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. /*---
  2. title: Call a web API
  3. group: Services
  4. summary: http.get and http.request answered by the rules in the HTTP window.
  5. 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}}}"}]}}}
  6. ---*/
  7. /*
  8. The playground has no network: open the HTTP window to change what each
  9. URL answers, add a delay, or make a request fail.
  10. */
  11. requirelib("http");
  12. // http.get returns the body as a string.
  13. var weather = JSON.parse(http.get("https://api.example.com/weather?city=Hong%20Kong"));
  14. // http.request returns status, headers and body, and does not throw.
  15. var res = http.request({
  16. url: "https://api.example.com/log",
  17. method: "POST",
  18. json: { user: USERNAME, temp: weather.temp }
  19. });
  20. // A URL no rule matches fails like an unreachable host.
  21. var down = http.request({ url: "https://unknown.example.org/" });
  22. sendJSONResp({
  23. weather: weather,
  24. logStatus: res.status,
  25. logBody: JSON.parse(res.body),
  26. unreachable: down.error
  27. });