Setting up a complete RESTful API with westack-go
Tags: go, mongodb, programming, tutorial
Published: 2023-05-07 09:13:13

westack-go is a powerful framework that allows you to easily create RESTful APIs in Go. It is designed to be simple, fast, and scalable, making it a great choice for building high traffic applications. In this tutorial, we will walk you through the steps of setting up a complete RESTful API with westack-go.

### Prerequisites

Before we begin, make sure you have the following installed on your system:

* Go ^1.20
* MongoDB  ^4.0

### Installing westack-go

To get started, create a new directory for your project and initialize a new Go module:

```shell
mkdir westack-go-example
cd westack-go-example
# Initialize the go project first
go mod init westack-go-example
```

Next, install **westack-go** using the following command:

```
go install github.com/fredyk/westack-go@v1.6
```

And finally, initialize the westack-go project:

```shell
westack-go init .
```

### Updating the Data Source File

westack-go uses the `server/datasources.json` file to manage data sources. In this tutorial, we'll be using MongoDB as our database. Once you run the `init` subcommand, your `datasources.json` file will be something like this:

```json
{
  "db": {
    "connector": "mongodb",
    "name": "db",
    "url": "mongodb://localhost:27017",
    "database": "westack_go_example",
    "user": "",
    "password": ""
  }
}
```

This configuration tells westack-go to connect to a MongoDB server running on `localhost:27017` and use a database named `westack_go_example`.

### Creating the models

Models are the representations of the data structures that are going to be used in the API. They define the attributes that are going to be stored, their types, relationships with other models and permissions.

The models are defined in JSON format and are loaded by the westack-go framework at runtime. This approach provides a lot of flexibility, as it allows you to define the data structure separately from the code that manipulates it, and also makes it easier to change the structure without modifying the code.

Here, we are adding a model named Note:

```shell
# Usage: westack-go model add <model_name> <datasource_name>
#   <datasource_name> defaults to "db" when you run `westack-go init .`
 
westack-go model add Note db
```

Because of the framework being highly oriented to security, any generated model won't allow any read or write operation without being authenticated at runtime.
In this case, we will skip authentication for `create` and read-type operations (`findMany`, `findById` and `count`) in our Note model, by setting proper Casbin policies in the `Note.json` file:

```json
{
  "name": "Note",
  "base": "PersistedModel",
  "public": true,
  "casbin": {
    "policies": [
      "$everyone,*,create,allow",
      "$everyone,*,read,allow"
    ]
  }
}
```

### Setting up our launcher

To start the server, add the following code to your `main.go` file:

```go
package main

import (
	"github.com/fredyk/westack-go/westack"
	"github.com/gofiber/fiber/v2"
	"log"
)

func main() {

	// Instantiate a new WeStack app
	app := westack.New()

	// Boot the app with a custom boot function
	app.Boot(func(app *westack.WeStack) {
		
		// Add a custom route
		app.Server.Get("/status", func(c *fiber.Ctx) error {
			return c.JSON(fiber.Map{"status": "ok"})
		})
		
	})

	// Start the app
	log.Fatal(app.Start())

}
```

The default listen port will be 8023. You can change it in the `server/config.json` file:

```json
{
  "name": "westack-go-example",
  "restApiRoot": "/api/v1",
  "port": 8023
}
```

You can also override it with the environment variable `PORT=8023`

### Starting the server

To start the server, you need to specify two required environment variables, and then just start

```shell
# (Please be sure to change both user and password)
export WST_ADMIN_USERNAME=myadminusername
export WST_ADMIN_PWD=myadminpassword

# Run the server:
go run main.go
```

If everything went well, it will output something like this:


![start output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p18yqlcr4ym9mqr817dr.png)

And a Swagger-UI will be generated and available at `http://localhost:8023/swagger`


![westack-go swagger ui](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d27m4ti3qtbedmpj8b9v.png)

### Testing it

Let's create an anonymous note:

![create anonymous note](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kfy84wr9zl67n8xa4lpo.png)

Response body:
```json
{
  "body": "This is an anonymous note",
  "created": "2023-05-07T16:29:23.661+02:00",
  "id": "6457b5c3fd9839449f0cc6f4",
  "modified": "2023-05-07T16:29:23.661+02:00",
  "title": "My first note"
}
```

And now let's confirm that the note was created with a simple `GET /api/v1/notes` request to find all notes:


![find many notes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7o59yazhl7hnvf1fdi9g.png)

### Summary

In this post, we've covered how to set up a complete RESTful API with westack-go in less than 10 minutes. westack-go is a powerful framework that can save you a lot of time and effort in building your next Go project. With its built-in ORM, automatic route generation, and middleware support, you can quickly create a scalable and maintainable API without having to write a lot of boilerplate code.

westack-go is a relatively new framework, but current contributors do their best to improve and extend its features, and we are hoping to grow our staff soon. If you're interested in learning more about westack-go, you can check out the official documentation on [Github](https://github.com/fredyk/westack-go/) or join the community on [Discord](https://discord.gg/tFRYbGQWjZ).

We hope you found this tutorial helpful and that it helps you get started with building your next API with westack-go!

### Refer to

* [westack-go official website](https://github.com/fredyk/westack-go/)
* [westack-go official Discord](https://discord.gg/tFRYbGQWjZ)
* [Go Fiber web framework](https://gofiber.io/)