Examples

Go REST API

Building a REST API

Go REST API with Gin handles CRUD with JSON responses.

Introduction to Gin Framework

The Gin framework is a popular web framework for Go, known for its performance and simplicity. It is particularly useful for building RESTful APIs due to its fast HTTP router and small memory footprint.

In this tutorial, we'll explore how to build a basic REST API using Gin to handle CRUD (Create, Read, Update, Delete) operations with JSON responses.

Setting Up Your Project

First, ensure that you have Go installed on your machine. You can download and install it from the official Go website. Once installed, set up your project:

  1. Create a new directory for your project and navigate into it:
  1. Initialize a new Go module:
  1. Install the Gin framework:

Creating the Main Application File

Next, create a new file named main.go and open it in your preferred code editor. This file will contain the main logic for your API.

Defining the CRUD Routes

Let's define the CRUD routes for our REST API. We'll create a simple API to manage a list of books. First, define a Book struct:

Next, add routes for each CRUD operation:

Testing Your API

After setting up your routes, you can test your API using tools like Postman or curl. Start your server with:

Then, send HTTP requests to test the various endpoints:

  • GET http://localhost:8080/books to retrieve all books.
  • POST http://localhost:8080/books with a JSON payload to add a new book.
  • PUT http://localhost:8080/books/:id with a JSON payload to update a book.
  • DELETE http://localhost:8080/books/:id to delete a book.
Previous
ORM