Search code examples
google-cloud-functionsserverless-framework

How can I have multiple API endpoints for one Google Cloud Function?


I have a Google Cloud Function which contains multiple modules to be invoked on different paths.

I am using the serverless framework to deploy my functions, but it has the limitation of only one path per function.

I want to use multiple paths in one function just like we can in the AWS serverless framework.

Suppose a user cloud function will have two paths /user/add as well as /user/remove; both the paths should invoke the same function.

Something like this:

serverless.yml

functions:
  user:
    handler: handle
    events:
      - http: user/add
      - http: user/remove

How can I have multiple API endpoints for one GCF?


Solution

  • Yes, indeed there is no actual REST service backing up Google Cloud Functions. It uses out of the box HTTP triggers.

    To hustle the way around, I'm using my request payload to determine which action to perform. In the body, I'm adding a key named "path".

    For example, consider the Function USER.

    To add a user:

    {
      "path":"add",
      "body":{
        "first":"Jhon",
        "last":"Doe"
      }
    }
    

    To remove a user:

    {
      "path":"remove",
      "body":{
        "first":"Jhon",
        "last":"Doe"
      }
    }
    

    If your operations are purely CRUD, you can use request.method which offers verbs like GET, POST, PUT, DELETE to determine operations.