Get API & Fetching Data from MongoDB in Go - 05
Published: 2024-05-18 07:42:24

- First check the Go version by running the command 
```
go version
```

- Create a folder

```
mkdir <folder_name>
```

- Switch to created folder 

```
cd <folder_name>
```
 

- Initialize the go project by running the given command. You will get `go.mod` file.
```
go mod init <folder_name>
```


- Create a `main.go` file, use terminal or bash

```
notepad main.go 
touch main.go
```

- Let's write some basic code in `main.go` file. 

```go
package main 

import (
	"fmt"
)


func main () {
	fmt.Println("Hello From Go")
}

```

- Run the code by following command 

```
go run main.go 
```

- You will see this output in console 

```
Hello From Go
```

- Install some packages to connect MongoDB. Here are commands
```
go get go.mongodb.org/mongo-driver
go get go.mongodb.org/mongo-driver/mongo
```

- Revisit the `main.go` file to connect MongoDB. Add some code to connect MongoDB. This is how it will look after adding.  

```go
package main 

// package importing
import (
    "fmt"

	"log"
	"context"

	"go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)


// mongodb connections
var collection *mongo.Collection
var ctx = context.TODO()

func init() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/")
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatal(err)
    }

    // check connection
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")

    collection = client.Database("testingWithGo").Collection("movies")
}



// entry point 
func main () {
    fmt.Println("Hello From Go")
}
```

- Run the code by following command

```
go run main.go 
```

- You will see this output in console

```
Connected to MongoDB!
Hello From Go
```

- Till, Our MongoDB is connected. Now let's add some data. We are going to add movie data. So, let's make a movie structure. 

```go
// movie model or structure 
type Movie struct {
	ID    string `json:"id"`
	Title string `json:"title"`
}
```

- Now write a function to add movie to database. 

```go
// to add movie to db
func addMovie(id, title string) {

	movie := Movie{
		ID:    id,
		Title: title,
	}

	_, err := collection.InsertOne(ctx, movie)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Movie added successfully!")
}
```

- Call the addMovie function to main function. 

```go
addMovie("1", "Captain America")
```

- This is how our code will look like after completing above steps

```go
package main 

// package importing
import (
    "fmt"

	"log"
	"context"

	"go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)




// mongodb connections
var collection *mongo.Collection
var ctx = context.TODO()

func init() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/")
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatal(err)
    }

    // check connection
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")

    collection = client.Database("testingWithGo").Collection("movies")
}



// movie model or structure 
type Movie struct {
	ID    string `json:"id"`
	Title string `json:"title"`
}


// to add movie to db
func addMovie(id, title string) {

	movie := Movie{
		ID:    id,
		Title: title,
	}

	_, err := collection.InsertOne(ctx, movie)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Movie added successfully!")
}




// entry point 
func main () {
    fmt.Println("Hello From Go")

	// callig addMovie 
	addMovie("1", "Captain America")
}
```

- Run the code by following command 

```
go run main.go 
```

- You will see this output in console

```
Connected to MongoDB!
Hello From Go
Movie added successfully!
```

- We have successfully added some data to MongoDB, you can verify in your database, which is your localhost. 

```
mongodb://localhost:27017/
```

- Now import these packages 

```
"encoding/json"
"net/http"
"go.mongodb.org/mongo-driver/bson"
```

- This how our import will look like 

```go
// package importing
import (
    "fmt"

	"log"
	"context"

	"encoding/json"
	"net/http"
        
        "go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

```

- Now write a function to getAllMovies. Here is the code

```go
// api to get all movies
func getAllMovies(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	// Define a slice to store the decoded documents
	var movies []Movie

	// Find all movies in the collection
	cursor, err := collection.Find(ctx, bson.M{})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer cursor.Close(ctx)

	// Iterate through the cursor and decode each document
	for cursor.Next(ctx) {
		var movie Movie
		if err := cursor.Decode(&movie); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		movies = append(movies, movie)
	}

	// Check for cursor errors after iterating
	if err := cursor.Err(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Encode the movies slice as JSON and write it to the response
	if err := json.NewEncoder(w).Encode(movies); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
```

- Call the getAllMovies with route in main, also run the server. 

```go
        // api to getAllMovies 
	http.HandleFunc("/movies", getAllMovies)

	// our server on port on 8000
	http.ListenAndServe(":8000", nil)
```

- Let's have a full code, after completing all the above steps

```go
package main 

// package importing
import (
    "fmt"

	"log"
	"context"

	"encoding/json"
	"net/http"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)




// mongodb connections
var collection *mongo.Collection
var ctx = context.TODO()

func init() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/")
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatal(err)
    }

    // check connection
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")

    collection = client.Database("testingWithGo").Collection("movies")
}



// movie model or structure 
type Movie struct {
	ID    string `json:"id"`
	Title string `json:"title"`
}


// to add movie to db
func addMovie(id, title string) {

	movie := Movie{
		ID:    id,
		Title: title,
	}

	_, err := collection.InsertOne(ctx, movie)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Movie added successfully!")
}





// api to get all movies
func getAllMovies(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	// Define a slice to store the decoded documents
	var movies []Movie

	// Find all movies in the collection
	cursor, err := collection.Find(ctx, bson.M{})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer cursor.Close(ctx)

	// Iterate through the cursor and decode each document
	for cursor.Next(ctx) {
		var movie Movie
		if err := cursor.Decode(&movie); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		movies = append(movies, movie)
	}

	// Check for cursor errors after iterating
	if err := cursor.Err(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Encode the movies slice as JSON and write it to the response
	if err := json.NewEncoder(w).Encode(movies); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}






// entry point 
func main () {
    fmt.Println("Hello From Go")

	// callig addMovie 
	addMovie("1", "Captain America")

	// api to getAllMovies 
	http.HandleFunc("/movies", getAllMovies)

	// visit this url in browser
	fmt.Println("Your Server is running on http://localhost:8000")

	// our server on port on 8000
	http.ListenAndServe(":8000", nil)
}
```

- Run the code by following command

```
go run main.go 
```

- You will see this output in console

```
Connected to MongoDB!
Hello From Go
Movie added successfully!
Your Server is running on http://localhost:8000

```

- Visit `http://localhost:8000/movies` on browser to verify the API. This what you will get.  

```javascript
[
    {
        "id": "1",
        "title": "The Shawshank Redemption"
    },
    {
        "id": "1",
        "title": "The Shawshank Redemption"
    },
    {
        "id": "1",
        "title": "Captain America"
    },
    {
        "id": "1",
        "title": "Captain America"
    },
    {
        "id": "1",
        "title": "Captain America"
    },
    {
        "id": "1",
        "title": "Captain America"
    }
]
```


That's for this article. Thank You.