How to Create a CRUD API With Golang’s Gin and MongoDB
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.
Initial Setup and Installation
Get started with Golangby 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, opena 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 thego.modfile. 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, useGin Gonicto route the API endpoints:
Now install the MongoDB Driver to store data:

How to Connect Go to MongoDB
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 itdatabases. Create a Go file inside this folder and name itdatabase.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.envfileusing the dotenv package. This makes your code more portable and comes in handy when using aMongoDB cloud cluster instance, for example.
TheConnectDBfunction establishes a connection and returns a new MongoDB Client object.
Create Database Collection
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, ismyGoappDB, withPostsas its collection.
Create the Database Model
Make a new folder inside your root directory and call itmodel. This folder handles your database model.
Create a new Go file inside that folder and call itmodel.go. Your model, in this case, is a blog post with its title:
Creating a CRUD API With Go
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 itroutes.
Create a separate Go file in this folder for each action. For example, you can name themcreate.go,read.go,update.go, anddelete.go. You’ll export these handlers as theroutespackage.
How to Create the POST Endpoint in Go
Start by defining the POST endpoint to write data into the database.
Insideroutes/create.go, add the following:
This code starts by importing the project’s custom modules. It then imports third-party packages includingGinandMongoDB Driver.
Further,postCollectionholds the database collection. Notably,c.BindJSON(“post”)is a JSONified model instance that calls each model field aspostPayload; this goes into the database.
How to Create the GET Endpoint
The GET endpoint, inroutes/read.go, reads a single document from the database via its unique ID. It also starts by importing custom and third-party packages:
ThepostIdvariable is a parameter declaration. It gets a document’s object ID asobjId.
However,resultis an instance of the database model, which later holds the returned document asres.
How to Create the PUT Endpoint
The PUT handler, inroutes/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$setoperator to update a required document called by its object ID.
Theresult.MatchedCountcondition prevents the code from running if there’s no record in the database or the passed ID is invalid.
Creating a DELETE Endpoint
The DELETE endpoint, indelete.go, removes a document based on the object ID passed as a URL parameter:
This code deletes a record using theDeleteOnefunction. It also uses theresult.DeletedCountproperty to prevent the code from running if the database is empty or the object ID is invalid.
Create the API Runner File
Finally, create amain.goinside 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 theroutervariable, agininstance that evokes the HTTP actions and calls each endpoint by its function name from theroutespackage.
Your CRUD project runs onlocalhost:3000. To run the server andtest the CRUD API, run the following command in your base directory:
Turn Your Golang CRUD Project Into a Usable Product
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.
Should you learn Go? Find out more about job prospects, level of difficulty, and Golang-specific features in this article.
So much time invested, and for what?
You don’t need to fork out for expensive hardware to run an AI on your PC.
Unlock a world of entertainment possibilities with this clever TV hack.
I gripped my chair the entire time—and then kept thinking about it when the screen turned off.
This small feature makes a massive difference.