08-http-mock.agi 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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 for a reply with any
  15. // status code.
  16. var res = http.request({
  17. url: "https://api.example.com/log",
  18. method: "POST",
  19. json: { user: USERNAME, temp: weather.temp }
  20. });
  21. // A URL no rule matches fails like an unreachable host: a request that gets
  22. // no reply throws an HTTPError.
  23. var unreachable = null;
  24. try {
  25. http.request({ url: "https://unknown.example.org/" });
  26. } catch (e) {
  27. unreachable = e.name + ": " + e.message;
  28. }
  29. sendJSONResp({
  30. weather: weather,
  31. logStatus: res.status,
  32. logBody: JSON.parse(res.body),
  33. unreachable: unreachable
  34. });