17.7 C
New York
Thursday, September 29, 2022

How to Create a CRUD API With Golang's Gin and MongoDB – MUO – MakeUseOf

A basic API is easy to build in Go using the Gin library. Complement it with a MongoDB backend and your CRUD app will be up and running in no time.
Golang is one of the top-paying, in-demand programming languages with many applications. When paired with frameworks like Gin, Revel, and gorilla/mux, you can easily create an API with Go.
Learn how to create a CRUD API in Golang using the Gin HTTP framework.
Get started with Golang by installing it on your computer if you haven’t already done so.
Once installed, the next step is to create a project root folder on your machine and initialize a Go module in that root directory.
To do this, open a CLI, navigate to your project root folder and run:
You'll see your module name (e.g. CRUD_API) and its version when you open the go.mod file. All custom packages will come from this parent module. So any imported custom package takes the form:
Next, install the packages necessary for creating the CRUD API. In this case, use Gin Gonic to route the API endpoints:
Now install the MongoDB Driver to store data:
All you need is your MongoDB URI to connect Golang with the database. It typically looks like this if you're connecting to MongoDB Atlas locally:
Now create a new folder in your project root directory and call it databases. Create a Go file inside this folder and name it database.go.
This is your database package, and it starts by importing the required libraries:
It's best practice to hide environment variables like the database connection string in a .env file using the dotenv package. This makes your code more portable and comes in handy when using a MongoDB cloud cluster instance, for example.
The ConnectDB function establishes a connection and returns a new MongoDB Client object.
MongoDB stores data in Collections, which provide an interface to the underlying database data.
To handle the collection-fetching functionality, start by creating a new folder, Collection, in your project root. Now create a new Go file, getCollection.go, that gets the collection from the database:
This function gets the Collection from the MongoDB database. The database name, in this case, is myGoappDB, with Posts as its collection.
Make a new folder inside your root directory and call it model. This folder handles your database model.
Create a new Go file inside that folder and call it model.go. Your model, in this case, is a blog post with its title:
Next up is the CRUD API creation. To start with this section, make a new folder within your project root directory to handle your endpoints. Call it routes.
Create a separate Go file in this folder for each action. For example, you can name them create.go, read.go, update.go, and delete.go. You’ll export these handlers as the routes package.
Start by defining the POST endpoint to write data into the database.
Inside routes/create.go, add the following:
This code starts by importing the project's custom modules. It then imports third-party packages including Gin and MongoDB Driver.
Further, postCollection holds the database collection. Notably, c.BindJSON("post") is a JSONified model instance that calls each model field as postPayload; this goes into the database.
The GET endpoint, in routes/read.go, reads a single document from the database via its unique ID. It also starts by importing custom and third-party packages:
The postId variable is a parameter declaration. It gets a document's object ID as objId.
However, result is an instance of the database model, which later holds the returned document as res.
The PUT handler, in routes/update.go, is similar to the POST handler. This time, it updates an existing post by its unique object ID:
A JSON format of the model instance (post) calls each model field from the database. The result variable uses the MongoDB $set operator to update a required document called by its object ID.
The result.MatchedCount condition prevents the code from running if there's no record in the database or the passed ID is invalid.
The DELETE endpoint, in delete.go, removes a document based on the object ID passed as a URL parameter:
This code deletes a record using the DeleteOne function. It also uses the result.DeletedCount property to prevent the code from running if the database is empty or the object ID is invalid.
Finally, create a main.go inside your project root directory. Your final project structure should look like this:
This file handles router execution for each endpoint:
This file is the main package that runs other files. It starts by importing the route handlers. Next is the router variable, a gin instance that evokes the HTTP actions and calls each endpoint by its function name from the routes package.
Your CRUD project runs on localhost:3000. To run the server and test the CRUD API, run the following command in your base directory:
You've successfully created a CRUD API with Go; congratulations! While this is a minor project, you've seen what it takes to execute regular HTTP requests in Go.
You can get more creative by expanding this into a more practical application that delivers value to users. Go is a suitable programming language for a range of use cases.
Idowu took writing as a profession in 2019 to communicate his programming and overall tech skills. At MUO, he covers coding explainers on several programming languages, cyber security topics, productivity, and other tech verticals. Idowu holds an MSc in Environmental Microbiology. But he sought out values outside his field to learn how to program and write technical explainers, enhancing his skill set. And he hasn’t looked back since then.
Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!


Related Articles


Please enter your comment!
Please enter your name here

Latest Articles