오류, JSON 및 상태 코드를 통한 API 이해
Source: Dev.to
Introduction
API를 파티에 있는 내성적인 사람에 비유하곤 했어요: 언제 반응할지, 아니면 완전히 무시할지 모른다는 느낌이었죠. 처음 API를 배우기 시작했을 때는 완전히 어두운 터널에 있는 기분이었습니다.
시간이 지나면서 조금씩 나아졌습니다. GET과 POST 요청이 어떻게 동작하는지, JSON에서 오류를 어떻게 처리하는지, 올바른 HTTP 상태 코드를 보내는 것이 왜 중요한지를 배웠죠. 이들은 사소해 보일 수 있지만, API를 예측 가능하고, 전문적이며, 사용자가 친숙하게 만들게 합니다.
Key Lessons
GET vs POST
- GET은 데이터를 조회합니다.
- POST는 데이터를 전송합니다.
이를 올바르게 사용하는 것이 모든 API의 기본입니다.
Error Handling
JSON 형태의 명확한 오류 메시지는 클라이언트가 무엇이 잘못됐는지, 어떻게 고쳐야 하는지를 이해하는 데 도움을 줍니다.
Status Codes Matter
적절한 HTTP 상태 코드를 사용하면 응답 본문을 자세히 살펴보지 않아도 요청 결과를 전달할 수 있습니다. 예시:
200 OK– 요청 성공400 Bad Request– 클라이언트가 잘못된 데이터를 보냈음401 Unauthorized– 인증이 필요하거나 실패함
Go Example
A small Go program 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
Using curl
curl -X POST http://localhost:8080/greet \
-H "Content-Type: application/json" \
-d '{"name":"Charity"}'
Response
{"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; you’ll see the greeting returned.
Conclusion
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, transforming something that once seemed intimidating into a tool you can confidently build with.
APIs may have seemed introverted at first, but once you speak their language, they’re actually pretty friendly.