#2572 how to call REST Api

Mohan Raj S Wed 19 Oct 2016

i am trying to call a REST Api and need to get the json result to a string. Help me with a sample method to consume a REST Api.

SlimerDude Wed 19 Oct 2016

Hi Mohan Raj!

If you're just using the core Fantom libraries, then you'd use web::WebClient:

string := WebClient(`http://example.com/api/`).getStr

Note you can't re-use WebClient instances between requests.

See the Web Client Examples for more.


But for a more versatile approach that uses Middleware (in a similar way to Ruby's Faraday library) then use the Butter library.

string := Butter.churnOut().get(`http://example.com/api/`).body.str

Note that Butter instances are reusable, and handles cookies and redirects. Butter can throw Errs on non 200 response codes, has an API for creating MultipartForm, and abstracts common HTTP headers into special clasess.

The Butter docs even have a section on Calling RESTful Services

Mohan Raj S Wed 19 Oct 2016

hi slimerDude,

i was tried with Web Client libraries with your given examples link, but i get an error in javascript console.

Error: Uncaught TypeError: Cannot read property 'make' of undefined

Now i tried with Butter library also. Still getting an error like,

Error: Uncaught TypeError: Cannot read property 'butter' of undefined

SlimerDude Wed 19 Oct 2016

i get an error in javascript console.

Oh, you're using Fantom in a browser! In that case, neither WebClient nor Butter have Javascript implementations.

To make a REST call from Javascript, try using the dom library and the HttpReq class.

Login or Signup to reply.