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 been a trend in modern software architecting for years.
There are a few reasons that I do like serverless API
Before we start, 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
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.
If you look at the my-apis project, you should see a Makefile
with the following contents at the project's root.
.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 must 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 endpoint created.
https://.execute-api..amazonaws.com/hello
https://.execute-api..amazonaws.com/world
You can click on any endpoint above and see the message below.
{"message":"Go Serverless v1.0! Your function executed successfully!"}
That's it! We have created two simple APIs without even writing any codes yet. Next, we will create a new API that returns a JSON.
First, let's create a new folder named my-first-api
and then create a main.go
file in the folder. Add the following content in the main.go
file.
package main
import (
"bytes"
"context"
"encoding/json"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
type Response events.APIGatewayProxyResponse
func Handler(ctx context.Context) (Response, error) {
var buf bytes.Buffer
body, err := json.Marshal(map[string]interface{}{
"message": "I have created a new Golang API!",
})
if err != nil {
return Response{StatusCode: 404}, err
}
json.HTMLEscape(&buf, body)
resp := Response{
StatusCode: 200,
IsBase64Encoded: false,
Body: buf.String(),
Headers: map[string]string{
"Content-Type": "application/json",
},
}
return resp, nil
}
func main() {
lambda.Start(Handler)
}
After that, we need to define a new function in the serverless.yml
file so that Serverless Framework will deploy the new API to API Lambda and integrate it with AWS API Gateway.
# Other configurations
functions:
# Other functions
# New API definition
myFirstApi:
handler: bin/my-first-api # Destination of the built folder for the API
events:
- httpApi:
path: /my-first-api # You can define any path for the API
method: get # Request method for the API
Last but not least, we must build the new API before deploying it to AWS Lambda. Add a new line in the build
command in the Makefile
.
# Other commands
build:
# Other build commands
env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o bin/my-first-api my-first-api/main.go
We are all prepared at this stage. We need to run the make deploy
command again, and the Serverless Framework will deploy the new Golang API to AWS Lambda. Similar to the initial deployment, the APIs' endpoint will be printed in the console. The new API's endpoint should look like this:
https://.execute-api..amazonaws.com/my-first-api
If you open the endpoint in the browser, you will see the JSON response.
{"message":"I have created a new Golang API!"}
Overall, serverless Golang APIs provide a powerful, efficient, and cost-effective solution for building APIs, making them attractive to many businesses and developers. I hope you can see how easy for us to create the Serverless API in less than a few commands.
Copyright © 2024 Tek Min Ewe