0

Is there a standard out-of-the-box way to access an API using GET or POST in TypeScript?

I only find libaries that do that like fetch or superagent suggested here when using React or HttpClient suggested here when using React.

I wonder though if there is a plain an simple way from within TypeScript to consume a REST API.

Socrates
  • 8,724
  • 25
  • 66
  • 113
  • 2
    `fetch` linked above is a built-in in most modern browsers and doesn't require any external libraries. If you're writing JS for the browser it probably *is* the most plain and simple way to consume a REST API. Also note that there's nothing specific here re: TypeScript, as TS only provides typing, not runtime behavior. – y2bd Aug 01 '18 at 21:54

1 Answers1

3

I wonder though if there is a plain an simple way from within TypeScript to consume a REST API.

Lets simplify REST API to be *I want to make GET and POST requests. The fact that it is a REST style API is not relevant.

I want to make GET and POST requests

Native ways of doing this depends on the JavaScript environment. e.g. Browser's traditional API has been XMLHttpRqeuest : https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest which is fully supported by TypeScript. A newer API is fetch which is also supported by TypeScript but might not be supported by the browser you are targetting.

On node you would use http module https://nodejs.org/api/http.html

Suggestion

Now if you want an API that works across both node and old browsers you will need some library that abstracts the native features. One suggestion is axios which works with TypeScript out of the box.

basarat
  • 261,912
  • 58
  • 460
  • 511
  • 2
    Also try `isomorphic-fetch` which uses the browsers fetch or `node-fetch` when on the server. – styfle Aug 02 '18 at 14:04