Create REST API in Golang with Serverless Framework and AWS

Today, we are learning how to create a basic serverless Golang API with Serverless Framework and deploy it to AWS Lambda and AWS API Gateway. Serverless API or FaaS (Function as a Service) has become a trend in modern software architecting for years.

There are a few reasons that I do like about serverless API

  • It saves more costs compared to hosting your API in the long run machine if you have fewer requests.
  •  It comes with auto-scaling to accommodate your traffic pattern.
  •  Easy to build as you can isolate each API.

Configure AWS Credentials

Before we get started, we have to set up AWS credentials to allow us to deploy the APIs to AWS. You may need to create a new AWS IAM user with that AdministratorAccess policy.

$ aws configure
AWS Access Key ID (None): aws_access_key_id
AWS Secret Access Key (None): aws_secret_access_key
Default region name (None): us-east-2
Default output format (None): json

Getting Started

First, let’s create the project for our serverless API. The Serverless CLI provides a simple command to create a template project for us to start developing.

$ npm install -g serverless
$ serverless create -t aws-go -p my-apis

Next, we need to install the go modules.

$ cd my-apis
$ go mod init myApi
$ go mod tidy

Now, we have all the dependencies installed.

Deploying to AWS

If you look at the my-apis project, you should be able to see a Makefile at the root of the project with the following contents.

.PHONY: build clean deploy

build:
	env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o bin/hello hello/main.go
	env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o bin/world world/main.go

clean:
	rm -rf ./bin

deploy: clean build
	sls deploy --verbose

NOTE: You will have to add a new line in the build command every time you add a new API.

We will be using the deploy command to deploy to AWS.

$ make deploy

Once the deployment is successful, you will see the endpoints of the API created.

https://<RANDOM_HASH>.execute-api.<REGION>.amazonaws.com/hello
https://<RANDOM_HASH>.execute-api.<REGION>.amazonaws.com/world

That’s it! We have created two simple APIs without even writing any codes yet. I’m just joking…I will leave that to you to build the API you want.

Conclusion

I hope you can see how easy for us to create the Serverless API in less than a few commands.

Leave a Reply Cancel reply

Exit mobile version
%%footer%%