Best practices querying APIs via cloud functions
Elias Günther

Elias Günther @eliasguenther

Location:
Hannover, Germany
Joined:
Oct 4, 2018

Best practices querying APIs via cloud functions

Publish Date: Jan 22 '20
7 2

Im currently working on a little side project where I want to query an api via cloud functions.

The API has several endpoints, say "Users" and "Posts".

Do I create one function for each endpoint? ie:


getUser(id) => Userdata
getPost(id) => Postdata

Enter fullscreen mode Exit fullscreen mode

OR do I create one single function that chooses the endpoint via a given paramenter:


getApiData("user", id) => Userdata
getApiData("post", id) => Postdata

Enter fullscreen mode Exit fullscreen mode

Are there any best practices? What are the pros and cons? How do you do it?

Comments 2 total

  • Eddie Hale
    Eddie HaleJan 22, 2020

    Architecturally I don't believe there is a best practice with Cloud Functions specifically. Your idea of injecting the endpoint makes it flexible for any future APIs you have, and would follow the SOLID design principles.

    You could send an object with all necessary data and only have one function, using a library like request. Then all you have to do is structure your input parameters to match.

    Something like this:

    var options = {
      baseUrl: 'https://localhost:3001',
      uri: '/api/user',
      method: 'GET',
      headers: {
        date: new Date().toUTCString(),
      }
    }
    
    makeApiRequest(options)
    
    var options = {
      baseUrl: 'https://localhost:3001',
      uri: '/api/user',
      method: 'POST',
      headers: {
        date: new Date().toUTCString(),
      }
      body: {
        firstName: 'Eddie'
        lastName: 'Hale'
      }
    }
    
    makeApiRequest(options)
    
    function makeApiRequest(options) {
      request(options, (err, response) => {
        if(err) console.log(err);
        else {
          console.log(response);
        }
      }
    }
    
  • Robert Carlson
    Robert CarlsonJan 22, 2020

    Great question, when building an API you should always consider your audience. An API is meant to communicate what can be done?. With that in mind, I would always encourage functions specific to the data it manipulates.

    That being said, if your API allows for any possible type of data to be stored or retrieved (such as 'foo'), than your approach is valid!

    Just think, how can I communicate best what options are available?

    WARNING; shameless plug:
    Your code is remarkably similar to our free tool meshydb. I would encourage you to check it out. It actually aligns well with your project.

Add comment