Build Simple Go REST API In Seconds

For those who need local Go REST API service ASAP without unnecessary details.

Denis Peganov
2 min readJan 23, 2023

Git repo link: https://github.com/disegmvm/Simple-Go-Rest-Api

There are many tutorials of how to create local Go API service, but all of them are having long introduction and 100-lines theory. Here you will get your local Go REST API service just in secods.

  • Your API will provide access to a car store, where each car has:
    - ID
    - Title

    - Color
  • You will be able to:
    - GET a list of all cars
    - GET a car by it’s ID
    -
    POST a new car
    - DELETE an existing car.

Let’s get started!

  1. Run go mod init <new-module-name> in your new service’s folder.
  2. Create main.go file in the same folder and paste the following code:

3. Run go get github.com/gin-gonic/gin in your service’s folder to get needed dependency.

4. Run go run main.go in that folder, and if you see [GIN-debug] Listening and serving HTTP on localhost:8080 then you have successfully launched your API.

5. Now in another terminal window you can:

  • GET a list of all cars:
    curl http://localhost:8080/cars \
    — header “Content-Type: application/json” \
    — request “GET”
  • GET a car by it’s ID:
    curl http://localhost:8080/cars/1 \
    — header “Content-Type: application/json” \
    — request “GET”
  • POST a new car:
    curl http://localhost:8080/cars \
    — include \
    — header “Content-Type: application/json” \
    — request “POST” \
    — data ‘{“id”: 101,”title”: “GM”,”color”: “White”}’
  • DELETE an existing car by it’s ID:
    curl http://localhost:8080/cars/2 \
    — header “Content-Type: application/json” \
    — request “DELETE”

Done! 🎉
Now you can go ahead and do whatever you need with your own API.

For those who need more details about above code.

In the API you’ve just created Gin framework is used. There are many Go web frameworks available, but I prefer Gin since it updates regulary and has great performance.
Also you can expand your code with more methods such as PUT and PATCH, as well as tie this up with a database so that it will be returning real values. It’s all up to you now.

Complete code with detailed comments:

--

--

Denis Peganov

Hey, I'm a QA Engineer dedicated to ensuring the quality of multiple products, and I'm passionate about sharing my expertise and insights with the community.