REST API with CRUD Operations
Start with REST API with CRUD Operations
Learn rest api with crud operations through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of rest api with crud operations.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A CRUD API creates, reads, updates and deletes resources through HTTP. Routes should return useful status codes and JSON representations while validating request bodies and resource ownership.
This compact in-memory API demonstrates POST and GET with Go’s standard HTTP router. Add update/delete and persistent storage in the next steps.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Completion checklist: use a sync.RWMutex or durable store, generate unique IDs, bound request bodies, reject unexpected fields when appropriate, implement PUT/PATCH/DELETE, add pagination and return consistent JSON errors. Test concurrent requests.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
}
func main() {
tasks := map[int]Task{}
mux := http.NewServeMux()
mux.HandleFunc("POST /tasks", func(w http.ResponseWriter, r *http.Request) {
var input Task
if err := json.NewDecoder(r.Body).Decode(&input); err != nil || strings.TrimSpace(input.Title) == "" {
http.Error(w, "invalid title", 400)
return
}
input.ID = 1
tasks[1] = input
w.WriteHeader(http.StatusCreated)
})
mux.HandleFunc("GET /tasks/1", func(w http.ResponseWriter, r *http.Request) {
task, ok := tasks[1]
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(task)
})
add := httptest.NewRecorder()
mux.ServeHTTP(add, httptest.NewRequest("POST", "/tasks", strings.NewReader(`{"title":"Learn Go"}`)))
get := httptest.NewRecorder()
mux.ServeHTTP(get, httptest.NewRequest("GET", "/tasks/1", nil))
fmt.Println("Create:", add.Code, "Read:", get.Code)
fmt.Print(get.Body.String())
}
Output
Create: 201 Read: 200
{"id":1,"title":"Learn Go"}Trace what the program does
The POST decodes a JSON title and saves one item, returning 201. The GET retrieves that item and returns JSON with an assigned ID.
Avoid common mistakes
- This in-memory map demo is not concurrency-safe if accessed by concurrent HTTP clients; use synchronization or a database.
- Real APIs need unique IDs, request size limits, full CRUD routes and authorization, not only the two sample paths.
Try it yourself
Implement GET /tasks, PATCH /tasks/{id} and DELETE /tasks/{id}; add a mutex and httptest coverage.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced REST API with CRUD Operations in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.