Skip to content

Connecting with APIs

Jakub Kopyto edited this page Dec 29, 2020 · 6 revisions

Connectig with APIs

  • Every single API should have its own service that will have implemented methods to communicate with it

Example:

export default class SportApiService extends ApiService {
   constructor(){
      super({
         API_KEY: process.env.SPORT_API_KEY
         API_LINK: `https://api.example.com/api_key=${process.env.SPORT_API_KEY}`
      })
   }
   
   async getAllTeams(){
      const res = await this.get(`${this.creds.API_LINK}/teams`)
      return res
   }
   
   async getTeamByName(teamName){
      const res = await this.get(`${this.creds.API_LINK}/teams?name=${teamName}`)
      return res
   }
}
  • After that it needs to be registered in main file: index.js
provider.provide("SportApi", new SportApiService())

Then, you can use your API in other JS files by typing const sportApi = provider.get("SportApi")

And calling proper method sportApi.getTeamByName("KoronaKielce")

You may wondering why are we getting API_KEY from process.env. It's due to security reasons. Every secrets like API keys can't be hardcoded in a plain text. They should be at least stored in environmental variables. You can put your own secrets in .env file

Here is the answer why are we extending ApiService: Why extending ApiService

Clone this wiki locally