DeveloperBreeze

Prerequisites

  • Go installed on your machine. If not, download and install it from the official Go website.
  • A code editor like Visual Studio Code or GoLand.
  • Basic knowledge of Go programming language.

Step 1: Setting Up the Project

  1. Create a new directory for your project:
   mkdir booksapi
   cd booksapi
  1. Initialize a new Go module:
   go mod init booksapi
  1. Install Gorilla Mux:
   go get -u github.com/gorilla/mux

Step 2: Defining the Book Model

Create a new file named models.go to define the data structure for a book:

package main

type Book struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Author string `json:"author"`
	Year   string `json:"year"`
}

Step 3: Setting Up the Main Application

Create a new file named main.go and set up the basic structure of the application:

package main

import (
	"encoding/json"
	"net/http"
	"github.com/gorilla/mux"
)

var books []Book

func main() {
	router := mux.NewRouter()

	// Define routes
	router.HandleFunc("/books", getBooks).Methods("GET")
	router.HandleFunc("/books/{id}", getBook).Methods("GET")
	router.HandleFunc("/books", createBook).Methods("POST")
	router.HandleFunc("/books/{id}", updateBook).Methods("PUT")
	router.HandleFunc("/books/{id}", deleteBook).Methods("DELETE")

	// Start the server
	http.ListenAndServe(":8000", router)
}

Step 4: Implementing the API Endpoints

Now, let's implement each of the endpoints.

1. Get All Books

Add the getBooks function to main.go:

func getBooks(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(books)
}

2. Get a Single Book

Add the getBook function to main.go:

func getBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for _, item := range books {
		if item.ID == params["id"] {
			json.NewEncoder(w).Encode(item)
			return
		}
	}
	json.NewEncoder(w).Encode(&Book{})
}

3. Create a New Book

Add the createBook function to main.go:

func createBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var book Book
	_ = json.NewDecoder(r.Body).Decode(&book)
	book.ID = "b" + string(len(books)+1) // Simple ID generation
	books = append(books, book)
	json.NewEncoder(w).Encode(book)
}

4. Update a Book

Add the updateBook function to main.go:

func updateBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for index, item := range books {
		if item.ID == params["id"] {
			books = append(books[:index], books[index+1:]...)
			var book Book
			_ = json.NewDecoder(r.Body).Decode(&book)
			book.ID = params["id"]
			books = append(books, book)
			json.NewEncoder(w).Encode(book)
			return
		}
	}
	json.NewEncoder(w).Encode(books)
}

5. Delete a Book

Add the deleteBook function to main.go:

func deleteBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for index, item := range books {
		if item.ID == params["id"] {
			books = append(books[:index], books[index+1:]...)
			break
		}
	}
	json.NewEncoder(w).Encode(books)
}

Step 5: Testing the API

Running the Server

Start the server by running the following command in your terminal:

go run main.go

The server should be running on http://localhost:8000.

Testing the Endpoints

You can use a tool like Postman or curl to test the endpoints.

  1. Get all books:
   curl -X GET http://localhost:8000/books
  1. Create a new book:
   curl -X POST http://localhost:8000/books -H "Content-Type: application/json" -d '{"title":"Go Programming","author":"John Doe","year":"2024"}'
  1. Get a single book:
   curl -X GET http://localhost:8000/books/b1
  1. Update a book:
   curl -X PUT http://localhost:8000/books/b1 -H "Content-Type: application/json" -d '{"title":"Advanced Go","author":"Jane Smith","year":"2024"}'
  1. Delete a book:
   curl -X DELETE http://localhost:8000/books/b1

Conclusion

In this tutorial, we built a simple RESTful API using Go and Gorilla Mux. We covered:

  • Setting up a Go project with Gorilla Mux.
  • Defining models and handling JSON data.
  • Implementing basic CRUD operations.
  • Testing the API using curl or Postman.

Next Steps

  • Implement authentication and authorization.
  • Add persistent storage using a database like PostgreSQL or MongoDB.
  • Explore more advanced routing and middleware options with Gorilla Mux.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

SQLite, combined with Node.js, offers a powerful and efficient way to manage data for your applications. Whether you're building a small utility or a larger application, understanding how to interact with databases is an invaluable skill.

Key Takeaways:

Oct 24, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

غالبًا ما يتم استخدام JSON في التفاعل مع واجهات برمجية (APIs) لجلب البيانات من الخادم. يمكنك استخدام fetch() في JavaScript لطلب بيانات JSON من API.

fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(response => response.json())
    .then(data => {
        console.log(data);
        console.log("الاسم:", data.name);
    })
    .catch(error => {
        console.error("حدث خطأ:", error);
    });

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX with XMLHttpRequest</title>
</head>
<body>
    <button id="fetchDataBtn">Fetch Data</button>
    <div id="dataOutput"></div>

    <script>
        document.getElementById('fetchDataBtn').addEventListener('click', function() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);

            xhr.onload = function() {
                if (this.status === 200) {
                    var data = JSON.parse(this.responseText);
                    document.getElementById('dataOutput').innerHTML = `
                        <h3>${data.title}</h3>
                        <p>${data.body}</p>
                    `;
                }
            };

            xhr.onerror = function() {
                console.error('Request failed.');
            };

            xhr.send();
        });
    </script>
</body>
</html>

In this example:

Sep 18, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

The response object contains several useful properties:

  • data: The actual data returned by the server.
  • status: The HTTP status code.
  • statusText: The HTTP status text.
  • headers: The headers sent by the server.

Sep 02, 2024
Read More
Tutorial
python

Getting Started with Pydantic: Data Validation and Type Coercion in Python

In this model, each attribute has a specified type. The is_active attribute also has a default value of True.

Pydantic automatically validates data and coerces types when you create an instance of the model:

Aug 29, 2024
Read More
Cheatsheet

REST API Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 24, 2024
Read More
Cheatsheet
mysql

MySQL Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 20, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

Create a form in React to submit new posts:

   function CreatePost() {
       const [title, setTitle] = useState('');
       const [body, setBody] = useState('');

       const handleSubmit = (event) => {
           event.preventDefault();

           axios.post('/api/posts', { title, body })
               .then(response => {
                   console.log('Post created:', response.data);
               })
               .catch(error => {
                   console.error('There was an error creating the post!', error);
               });
       };

       return (
           <form onSubmit={handleSubmit}>
               <div>
                   <label>Title:</label>
                   <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
               </div>
               <div>
                   <label>Body:</label>
                   <textarea value={body} onChange={(e) => setBody(e.target.value)}></textarea>
               </div>
               <button type="submit">Create Post</button>
           </form>
       );
   }

   export default CreatePost;

Aug 14, 2024
Read More
Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

This tutorial has covered the basics of setting up a GraphQL API with Node.js and Apollo Server, including creating queries, mutations, and subscriptions. By leveraging GraphQL's powerful features, you can build efficient, flexible, and scalable APIs for your applications.

  • Explore Authentication: Implement authentication and authorization to secure your GraphQL API.
  • Integrate with a Database: Connect your GraphQL server to a database for persistent data storage.
  • Optimize Performance: Use techniques like query batching and caching to improve API performance.

Aug 12, 2024
Read More
Code
nodejs graphql

GraphQL API Server with Node.js and Apollo Server

   mkdir graphql-server
   cd graphql-server
   npm init -y

Install the required packages:

Aug 12, 2024
Read More
Code
javascript json

How to Deep Clone a JavaScript Object

No preview available for this content.

Aug 12, 2024
Read More
Tutorial
python

Build a Web Application with Flask and PostgreSQL

In this tutorial, you'll learn how to build a web application using the Flask framework and PostgreSQL as the database. We'll cover the entire process, from setting up your environment to deploying your application.

  • Python Installed: Ensure Python 3.x is installed on your system.
  • Pip Package Manager: Ensure pip is installed for managing Python packages.
  • PostgreSQL: Install PostgreSQL and set up a database for your application.
  • Basic Python and SQL Knowledge: Familiarity with Python and SQL basics will be helpful.

Aug 04, 2024
Read More
Code
json python

Python Code Snippet: Simple RESTful API with FastAPI

No preview available for this content.

Aug 04, 2024
Read More
Code
javascript json

JavaScript Code Snippet: Fetch and Display Data from an API

No preview available for this content.

Aug 04, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

from flask import Flask, jsonify

app = Flask(__name__)

items = [
    {"id": 1, "name": "Item 1", "price": 100},
    {"id": 2, "name": "Item 2", "price": 150},
    {"id": 3, "name": "Item 3", "price": 200}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

if __name__ == '__main__':
    app.run(debug=True)
from flask import Flask, jsonify, request, abort

app = Flask(__name__)

items = [
    {"id": 1, "name": "Item 1", "price": 100},
    {"id": 2, "name": "Item 2", "price": 150},
    {"id": 3, "name": "Item 3", "price": 200}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    return jsonify(item)

@app.route('/api/items', methods=['POST'])
def create_item():
    if not request.json or 'name' not in request.json or 'price' not in request.json:
        abort(400)
    new_item = {
        "id": items[-1]['id'] + 1 if items else 1,
        "name": request.json['name'],
        "price": request.json['price']
    }
    items.append(new_item)
    return jsonify(new_item), 201

@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    if not request.json:
        abort(400)
    item['name'] = request.json.get('name', item['name'])
    item['price'] = request.json.get('price', item['price'])
    return jsonify(item)

@app.route('/api/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    items.remove(item)
    return jsonify({"result": True})

if __name__ == '__main__':
    app.run(debug=True)

Aug 03, 2024
Read More
Code
javascript

Fetch JSON Data from API in JavaScript

No preview available for this content.

Jan 26, 2024
Read More
Code
python

JSON Serialization and Deserialization

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Simple RESTful API in Node.js using Express

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Read JSON Data from a File

No preview available for this content.

Jan 26, 2024
Read More
Code
php

JSON File Reading and Decoding

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!