Skip to content

Instantly share code, notes, and snippets.

@JSONOrona
Last active August 14, 2023 19:54
Show Gist options
  • Save JSONOrona/896f30cc62b541a16c91951ab592bf8a to your computer and use it in GitHub Desktop.
Save JSONOrona/896f30cc62b541a16c91951ab592bf8a to your computer and use it in GitHub Desktop.

This is simple RESTful API for managing a list of notes. We'll use the gorilla/mux package to handle routing and create endpoints for creating, retrieving, updating, and deleting notes. And, yes it does work!

  1. Setting Up Your Project:

Create a new directory for the project and navigate to it:

mkdir note-api
cd note-api
  1. Initialize Go Module:

Initialize a Go module:

go mod init note-api
  1. Install Dependencies:

Install the gorilla/mux package for routing:

go get -u github.com/gorilla/mux@v1.8.0
  1. Create Main Go File:

Create a file named main.go with the following content:

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/gorilla/mux"
)

type Note struct {
	ID        int       `json:"id"`
	Title     string    `json:"title"`
	Content   string    `json:"content"`
	CreatedAt time.Time `json:"createdAt"`
}

var notes []Note
var currentID int

func createNoteHandler(w http.ResponseWriter, r *http.Request) {
	var note Note
	if err := json.NewDecoder(r.Body).Decode(&note); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	note.ID = currentID
	note.CreatedAt = time.Now()
	notes = append(notes, note)
	currentID++
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(note)
}

func getNotesHandler(w http.ResponseWriter, r *http.Request) {
	json.NewEncoder(w).Encode(notes)
}

func getNoteByIDHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	noteID, err := strconv.Atoi(vars["id"])
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	for _, note := range notes {
		if note.ID == noteID {
			json.NewEncoder(w).Encode(note)
			return
		}
	}
	http.NotFound(w, r)
}

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

	r.HandleFunc("/notes", createNoteHandler).Methods("POST")
	r.HandleFunc("/notes", getNotesHandler).Methods("GET")
	r.HandleFunc("/notes/{id:[0-9]+}", getNoteByIDHandler).Methods("GET")

	fmt.Println("Note API listening on http://localhost:8080")
	log.Fatal(http.ListenAndServe(":8080", r))
}
  1. Build and Run:

Build and run the project:

go build

Now you can use the tool to start the note API:

./note-api

You can interact with the API using tools like curl, Postman, or any other API client. Here are some example requests:

To create a new note:

curl -X POST -H "Content-Type: application/json" -d '{"title":"My Note","content":"This is my first note."}' http://localhost:8080/notes

To retrieve all notes:

curl http://localhost:8080/notes

To retrieve a note by ID (replace 1 with the actual note ID):

curl http://localhost:8080/notes/1

Please note that this example provides a basic implementation of a note API for educational purposes. In a production environment, you'd need to handle authentication, data persistence (such as using a database), and proper error handling.

Python Webapp Frontend for my notes program

  1. Update Python Web App:

Update the app.py file with the following content:

from flask import Flask, render_template, request, jsonify
import requests

app = Flask(__name__)

API_BASE_URL = "http://localhost:8080"

@app.route("/", methods=["GET"])
def index():
    return render_template("index.html")

@app.route("/notes", methods=["GET"])
def get_notes():
    response = requests.get(f"{API_BASE_URL}/notes")
    notes = response.json()
    return render_template("notes.html", notes=notes)

@app.route("/all-notes", methods=["GET"])
def get_all_notes():
    response = requests.get(f"{API_BASE_URL}/notes")
    notes = response.json()
    return render_template("all_notes.html", notes=notes)

@app.route("/notes", methods=["POST"])
def create_note():
    title = request.form["title"]
    content = request.form["content"]
    
    data = {
        "title": title,
        "content": content
    }
    
    response = requests.post(f"{API_BASE_URL}/notes", json=data)
    
    if response.status_code == 201:
        return jsonify({"message": "Note created successfully"})
    else:
        return jsonify({"error": "Failed to create note"}), 500

if __name__ == "__main__":
    app.run(debug=True)
  1. Create a New Template:

Create a new HTML file named all_notes.html inside the templates folder:

  • all_notes.html:
<!DOCTYPE html>
<html>
<head>
    <title>All Notes</title>
</head>
<body>
    <h1>All Notes</h1>
    <ul>
        {% for note in notes %}
        <li>
            <strong>{{ note.Title }}</strong><br>
            {{ note.Content }}<br>
            Created at: {{ note.CreatedAt }}
        </li>
        {% endfor %}
    </ul>
    <a href="/">Back to Home</a>
</body>
</html>
  1. Update index.html:

Update the index.html file to include a link to view all notes:

<!DOCTYPE html>
<html>
<head>
    <title>Note API Frontend</title>
</head>
<body>
    <h1>Note API Frontend</h1>
    <form action="/notes" method="POST">
        <label for="title">Title:</label>
        <input type="text" id="title" name="title" required><br>
        <label for="content">Content:</label>
        <textarea id="content" name="content" required></textarea><br>
        <button type="submit">Create Note</button>
    </form>

    <h2>Notes:</h2>
    <a href="/notes">View Notes</a><br>
    <a href="/all-notes">View All Notes</a>
</body>
</html>
  1. Run the Python Web App:

Run the updated Python web app using the following command:

python app.py

Now, when you navigate to http://127.0.0.1:5000/, you'll see a link to "View All Notes." Clicking on that link will take you to a page that displays all the notes stored in your Go API.

$uri = "http://localhost:8080/notes"
$headers = @{
"Content-Type" = "application/json"
}
$body = @{
"title" = "My Note"
"content" = "This is my first note."
} | ConvertTo-Json
$response = Invoke-RestMethod -Uri $uri -Method POST -Headers $headers -Body $body
$response | ConvertTo-Json -Depth 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment