I used to joke that APIs are like introverts at a party: you never know if they’ll respond or ignore you entirely. When I first started learning about them, I felt exactly like that completely in the dark.
Over time, I’ve gradually improved. I’ve learned how GET and POST requests work, how to handle errors in JSON, and why sending the correct HTTP status codes matters. These may seem small, but they make your API predictable, professional, and friendly for anyone consuming it.
Here are a few key lessons I’ve learned:
GET vs POST: GET retrieves data, POST sends data. Using them correctly is the foundation of any API.
Error Handling: Clear error messages in JSON help clients understand what went wrong and how to fix it.
Status Codes Matter: Using the right HTTP status code communicates the result of a request without needing to dig into the response body. Examples:
200 OK – request succeeded
400 Bad Request – client sent invalid data
401 Unauthorized – authentication required or failed
Here’s a small Go example I built that takes a user’s name and returns a personalized greeting:
package main
import (
"encoding/json"
"net/http"
)
type User struct {
Name string `json:"name"`
}
func greetHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var user User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid JSON"})
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "Hello " + user.Name})
}
func main() {
http.HandleFunc("/greet", greetHandler)
http.ListenAndServe(":8080", nil)
}
Testing the API
Once the server is running, you can test it easily:
Using curl:
curl -X POST http://localhost:8080/greet \
-H "Content-Type: application/json" \
-d '{"name":"Charity"}'
You should see:
{"message":"Hello Charity"}
Using Postman:
Open Postman and create a new POST request.
Set the URL to http://localhost:8080/greet.
In the body, select raw JSON and enter:
{"name":"Charity"}
Send the request and you’ll see the greeting returned.
Even this simple example reinforces why proper JSON formatting, error handling, and status codes are essential. Small improvements like these make APIs much easier to use and understand, and they transform something that once seemed intimidating into a tool I can confidently build with.
APIs may have seemed introverted at first, but once you speak their language, they’re actually pretty friendly.
Top comments (0)