오류, JSON 및 상태 코드를 통한 API 이해

발행: (2026년 2월 13일 오후 07:16 GMT+9)
3 분 소요
원문: Dev.to

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

  1. Open Postman and create a new POST request.
  2. Set the URL to http://localhost:8080/greet.
  3. In the body, select raw → JSON and enter:
{"name":"Charity"}
  1. 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.

0 조회
Back to Blog

관련 글

더 보기 »

Server Components는 SSR이 아니다!

SSR vs. React Server Components 개발 세계에서 React Server Components(RSC)는 종종 또 다른 형태의 Server‑Side Rendering(SSR)으로 오해받는다. 두 가지 모두…

📦Redux란 무엇인가?

프론트엔드 개발을 배우고 있다면, 특히 React와 함께라면 Redux에 대해 들어봤을 것입니다. 처음에는 혼란스러워 보일 수 있지만, 핵심 아이디어는 간단합니다....