Creating RESTful API with GO Entity Framework
By: Louis Aldorio
Tags: Entity Framework, Entity, Restful Api, Go, Graph

Have you ever struggled with determining which GO’s ORM library is best for you? the Go Ent Framework will be the best option for some use cases.

If your project is going to have large data models then this will be the best option for you.

Today I’m going to help you get started with this framework by creating a simple RESTful API with it. There are some features provided by this framework.

Schema As Code — model any database schema as Go objects.

— model any database schema as Go objects. Easily Traverse Any Graph — run queries, aggregations and traverse any graph structure easily.

— run queries, aggregations and traverse any graph structure easily. Statically Typed And Explicit API — 100% statically typed and explicit API using code generation.

— 100% statically typed and explicit API using code generation. Multi Storage Driver — supports MySQL, PostgreSQL, SQLite, and Gremlin.

— supports MySQL, PostgreSQL, SQLite, and Gremlin. Extendable — simple to extend and customize using Go templates.

Full Documentation: https://entgo.io/

It is developed and maintained by a8m and alexsn from the Facebook Connectivity team. This project is open-sourced since Feb 2020.

Requirement:

Basic knowledge of docker/ docker-compose(to start MySQL Database Instance Locally)

Go(Basic Understanding)

Library:

Gorilla Mux: https://github.com/gorilla/mux

repository: https://github.com/LouisAldorio/medium-entity-framework-RESTful-API

Let’s get started by initializing a new Project. We are going to create a todo list project as our use case to utilize this framework

mkdir Go-Entity-Framework-todolist

cd Go-Entity-Framework-todolist

go mod init myapp

Now, let’s get the module/ library needed for this project.

go get entgo.io/ent/cmd/ent

go get -u github.com/gorilla/mux

Everything is set, let’s write our first entity. Before that let’s break down how many entities do we need for this simple to-do app. So, we will have many users in our app and each user will have many todos to be fulfilled.

So their relation will be one to many relations between the User entity and the Todo entity.

Entities in Database.

Now let’s figure out their relation.

one to many relations

Okay, we have figured out what entity we are going to have and also the relation between them. Let’s implement it with the Entity Framework.

Open the terminal and run the following command to Initialize the User Entity.

go run entgo.io/ent/cmd/ent init User

And the Todo Entity.

go run entgo.io/ent/cmd/ent init Todo

What these commands do is that it will generate folders containing the basic template for us to write the properties of the entity and also define the relationships between entities with the Go Syntax determined by the Ent Framework itself.

Now your directory should look like this.

We will first go to the user.go, and define the relation to Todo Entity And the properties.

Explanation:

to define the properties/field that an Entity holds we can use the field package exported from the ent framework.

that an Entity holds we can use the field package exported from the ent framework. package edge exported from the ent framework will help up defining the relation from the current entity to others.

exported from the ent framework will help up defining the relation from the current entity to others. edge.To(), help us to define the one-to-many relationship .

. defining field ID is not necessary, it will be auto-added after the code generation.

Now let’s go to the todo.go and define the field and relationship.

Now, everything is done let’s run

go generate ./ent

this command should generate a lot of code and files inside the ent folder.

directory hierarchy

the code and file generated contain the method that helps us interact with the database, models, migrations, and many more. You can read more about the functionality of each file generated in the documentation.

link: https://entgo.io/docs/code-gen

We are going to create a new folder called service, this folder will contain 2 files userService.go and todoService.go.

And the userService.go

The above code is just the CRUD implementation for User and Todo Entity by calling the method generated by the ent framework.

Now, let’s create the “config” folder and a file name ent.go inside of the folder, this section will contain our database open connection setup, migrations, and also the accessor and mutator to access the Ent Client.

Now your folder hierarchy will look like below.

paste below code to ent.go

Next, we are going to implement controllers, that will help us extract the request’s Param. Url or body and also return the response as JSON format. briefly, the controller will act as a handler later in the router’s route.

Let’s create a folder named “controller” and create 2 new files which are:

userController.go

todoController.go

Before that, let’s create a “model” folder, that will hold our custom models. Currently, it will contain a file named “response.go” which is a Response Model that we will use to form our response and return it to the client.

We also need a folder called “utils” that will accommodate the helper method. So let’s create one. I will name it “response.go”.

We will keep using this method to form the response, encode the object to JSON and then return it to the client. So, it’s better to separate it into a different function that we won’t keep repeating ourselves.

Every dependency for the package controller is set, let’s write the controller :)

first, let’s implement the todoController.

and the userController.

After we have the route handlers which are controllers, we must implement the routing. Therefore, Create new folder named “router”. After that create 3 files inside the folder which are:

provider.go — will act as the entrypoint to access the package router, and register all the available router.

— will act as the entrypoint to access the package router, and register all the available router. userRouter.go — we will define the user router registrator function here.

— we will define the user router registrator function here. todoRouter.go — todo router registrator.

Current folder hierarchy

Let’s implement the todoRouter

And now the userRouter

now, all route has been defined but, we still have to create a universal route registrator in the provider.go file that will be called at the entry point of this project which is the server.go file that will be created later.

let’s now create the entry point of our project (server.go)

We are still missing something, which is a middleware, I’m not going to implement auth middleware but just a simple middleware that handles the header of every request and response transaction.

Let’s create a folder named “middleware” and a file in it called “header.go”

Don’t forget to import and let the router use it.

Now, we need to run MySQL Instance, let’s do this by using docker-compose to fire up the database container.

docker-compose up -d

And your database instance is running now. Also do not forget to add the “.vscode” folder the le “launch.json ” in it, so we can execute both the environment file and the entry point project file at the same time by hitting F5

On the first startup, the entity framework will start the database migration, and create the database table exactly the same as the entity graph we have defined in our code.

Now, let’s try to create a user and add a to-do to his profile.

create new user

Now let’s create a todo attach to the user.

Create Todo attach to the user with id 1

Get all users data included the todo attach to him.

The Ent framework also solves the problem of the N+1 database query. you can try to create more users and add more todo to each of the created users. if you pay attention to the log output you will find out that Ent has done eager loading in the query which is similar to Dataloader in Graphql.

hope this article can help all of you :)