/example-go-api

This is my first Api written using Go | https://shell.cloud.google.com/?walkthrough_tutorial_url=https%3A%2F%2Fraw.githubusercontent.com%2Fgolang%2Ftour%2Fmaster%2Ftutorial%2Fweb-service-gin.md&pli=1&show=ide&environment_deployment=ide

Primary LanguageGo

Example Go API

This is a simple RESTful API built with Go and the Gin framework. The API allows you to manage a collection of music albums.

Getting Started

Prerequisites

  • Go (version 1.23.5 or later)
  • Gin Web Framework

Installation

  1. Clone the repository:

    git clone https://github.com/chadidi/example-go-api.git
    cd example-go-api
  2. Install the Gin framework:

    go get .

Running the API

To start the API server, run:

go run .

The server will start on localhost:3000.

API Endpoints

Get all albums

  • URL: /albums
  • Method: GET
  • Response:
    [
        {
            "id": "1",
            "title": "Blue Train",
            "artist": "John Coltrane",
            "price": 56.99
        },
        {
            "id": "2",
            "title": "Jeru",
            "artist": "Gerry Mulligan",
            "price": 17.99
        },
        {
            "id": "3",
            "title": "Sarah Vaughan and Clifford Brown",
            "artist": "Sarah Vaughan",
            "price": 39.99
        }
    ]

Get album by ID

  • URL: /albums/:id
  • Method: GET
  • Response:
    {
        "id": "1",
        "title": "Blue Train",
        "artist": "John Coltrane",
        "price": 56.99
    }

Add a new album

  • URL: /albums
  • Method: POST
  • Request Body:
    {
        "id": "4",
        "title": "New Album",
        "artist": "New Artist",
        "price": 29.99
    }
  • Response:
    {
        "id": "4",
        "title": "New Album",
        "artist": "New Artist",
        "price": 29.99
    }

Code Overview

The main components of the API are:

  • album struct: Represents the data structure of an album.
  • albums slice: A slice to seed initial album data.
  • getAlbums function: Handles GET requests to retrieve all albums.
  • postAlbums function: Handles POST requests to add a new album.
  • getAlbumByID function: Handles GET requests to retrieve an album by its ID.
  • main function: Sets up the Gin router and routes, and starts the server.

License

This project is licensed under the MIT License.