Web API 기초 가이드 - glasslego/getting-started-with-python GitHub Wiki

Web API란?

웹 API는 인터넷을 통해 서버와 데이터를 주고받는 방법입니다. 마치 식당에서 웨이터에게 주문하고 음식을 받는 것과 비슷합니다.

주요 HTTP 메서드

GET - 데이터 가져오기

  • 서버에서 정보를 조회할 때 사용
  • 예: 사용자 목록 보기, 게시글 읽기

POST - 데이터 생성하기

  • 서버에 새로운 데이터를 생성할 때 사용
  • 예: 새 계정 만들기, 댓글 작성

PUT - 데이터 수정하기

  • 기존 데이터를 전체 수정할 때 사용
  • 예: 프로필 정보 업데이트

DELETE - 데이터 삭제하기

  • 서버에서 데이터를 삭제할 때 사용
  • 예: 게시글 삭제, 계정 탈퇴

Python으로 API 사용하기

1. requests 모듈 설치

pip install requests

2. 실제 사용 예시

import requests
import json

# API 기본 URL
BASE_URL = "https://jsonplaceholder.typicode.com"

# GET - 데이터 가져오기
def get_posts():
    response = requests.get(f"{BASE_URL}/posts")
    if response.status_code == 200:
        posts = response.json()
        print(f"게시글 {len(posts)}개를 가져왔습니다.")
        return posts
    else:
        print(f"오류 발생: {response.status_code}")

# POST - 새 데이터 생성
def create_post(title, body):
    data = {
        "title": title,
        "body": body,
        "userId": 1
    }
    response = requests.post(f"{BASE_URL}/posts", json=data)
    if response.status_code == 201:
        new_post = response.json()
        print(f"새 게시글이 생성되었습니다. ID: {new_post['id']}")
        return new_post
    else:
        print(f"생성 실패: {response.status_code}")

# PUT - 데이터 수정
def update_post(post_id, title, body):
    data = {
        "id": post_id,
        "title": title,
        "body": body,
        "userId": 1
    }
    response = requests.put(f"{BASE_URL}/posts/{post_id}", json=data)
    if response.status_code == 200:
        updated_post = response.json()
        print(f"게시글 {post_id}가 수정되었습니다.")
        return updated_post
    else:
        print(f"수정 실패: {response.status_code}")

# DELETE - 데이터 삭제
def delete_post(post_id):
    response = requests.delete(f"{BASE_URL}/posts/{post_id}")
    if response.status_code == 200:
        print(f"게시글 {post_id}가 삭제되었습니다.")
    else:
        print(f"삭제 실패: {response.status_code}")

# 사용 예시
if __name__ == "__main__":
    # 1. 게시글 목록 가져오기
    posts = get_posts()
    
    # 2. 새 게시글 생성
    new_post = create_post("테스트 제목", "테스트 내용입니다.")
    
    # 3. 게시글 수정
    if new_post:
        update_post(new_post['id'], "수정된 제목", "수정된 내용입니다.")
    
    # 4. 게시글 삭제
    if new_post:
        delete_post(new_post['id'])

상태 코드

  • 200: 성공
  • 201: 생성 성공
  • 400: 잘못된 요청
  • 404: 데이터를 찾을 수 없음
  • 500: 서버 오류

  1. 항상 상태 코드를 확인하세요
  2. json() 메서드로 응답을 파이썬 객체로 변환
  3. 예외 처리를 추가하면 더 안전합니다
  4. API 문서를 먼저 읽어보세요