WordPress REST API 완전 가이드





📋 목차

  1. WordPress REST API 개요
  2. 기본 설정 및 활성화
  3. 핵심 엔드포인트 활용
  4. 인증 방식 완벽 정리
  5. 실전 활용 예제
  6. 고급 기능 및 커스터마이징
  7. 보안 및 성능 최적화
  8. 문제 해결 및 디버깅

1. WordPress REST API 개요

1.1 REST API란?

WordPress REST API는 WordPress 사이트의 데이터를 JSON 형식으로 주고받을 수 있도록 해주는 강력한 인터페이스입니다. 이를 통해 외부 애플리케이션에서 WordPress 콘텐츠를 조회, 생성, 수정, 삭제할 수 있습니다.

1.2 주요 특징

  • RESTful 아키텍처 – HTTP 메서드(GET, POST, PUT, DELETE) 기반
  • JSON 형식 지원 – 구조화된 데이터 교환
  • 확장 가능 – 플러그인을 통한 엔드포인트 추가 및 수정
  • 비로그인 접근 – 공개 콘텐츠는 인증 없이 접근 가능
  • 다양한 인증 방식 – OAuth, JWT, Cookie 등 지원

1.3 활용 사례

  • 모바일 앱 개발
  • 헤드리스 CMS 구축
  • 외부 시스템과의 데이터 연동
  • 프론트엔드 JavaScript 프레임워크와 통합

2. 기본 설정 및 활성화

2.1 REST API 활성화 확인

WordPress 4.7 이상에서는 기본적으로 활성화되어 있습니다.

# API 엔드포인트 확인
curl -X GET "https://yourdomain.com/wp-json/wp/v2/"

2.2 permalinks 설정

REST API가 정상 작동하려면 permalinks가 활성화되어야 합니다.

WordPress 관리자 → 설정 → permalinks → 기본값 이외 선택

2.3 .htaccess 설정 (필요시)

# .htaccess 파일에 추가
RewriteEngine On
RewriteRule ^wp-json/(.*) /index.php?rest_route=/$1 [QSA,L]

3. 핵심 엔드포인트 활용

3.1 게시글 (Posts) 관리

📖 게시글 목록 조회

# 기본 조회
curl -X GET "https://yourdomain.com/wp-json/wp/v2/posts"

# 페이지네이션 및 정렬
curl -X GET "https://yourdomain.com/wp-json/wp/v2/posts?page=1&per_page=5&orderby=date&order=desc"

# 특정 카테고리 게시글
curl -X GET "https://yourdomain.com/wp-json/wp/v2/posts?categories=1"

응답 예제:

[
  {
    "id": 1,
    "date": "2024-01-15T10:30:00",
    "title": {
      "rendered": "WordPress REST API 시작하기"
    },
    "content": {
      "rendered": "<p>WordPress REST API 사용법을 알아보겠습니다.</p>"
    },
    "excerpt": {
      "rendered": "<p>WordPress REST API 기본 사용법</p>"
    },
    "author": 1,
    "categories": [1, 3],
    "tags": [5, 7],
    "status": "publish"
  }
]

📄 특정 게시글 조회

curl -X GET "https://yourdomain.com/wp-json/wp/v2/posts/1"

✏️ 게시글 생성 (인증 필요)

curl -X POST "https://yourdomain.com/wp-json/wp/v2/posts" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -d '{
       "title": "새로운 글 제목",
       "content": "이것은 REST API로 생성된 글입니다.",
       "status": "publish",
       "categories": [1],
       "tags": [2, 3],
       "excerpt": "글 요약입니다.",
       "featured_media": 123
     }'

🔄 게시글 수정

curl -X PUT "https://yourdomain.com/wp-json/wp/v2/posts/2" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -d '{
       "title": "수정된 제목",
       "content": "수정된 내용입니다."
     }'

🗑️ 게시글 삭제

# 휴지통으로 이동
curl -X DELETE "https://yourdomain.com/wp-json/wp/v2/posts/2" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

# 완전 삭제
curl -X DELETE "https://yourdomain.com/wp-json/wp/v2/posts/2?force=true" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

3.2 페이지 (Pages) 관리

# 페이지 목록 조회
curl -X GET "https://yourdomain.com/wp-json/wp/v2/pages"

# 특정 페이지 조회
curl -X GET "https://yourdomain.com/wp-json/wp/v2/pages/1"

3.3 카테고리 및 태그 관리

# 카테고리 목록
curl -X GET "https://yourdomain.com/wp-json/wp/v2/categories"

# 태그 목록
curl -X GET "https://yourdomain.com/wp-json/wp/v2/tags"

# 새 카테고리 생성 (인증 필요)
curl -X POST "https://yourdomain.com/wp-json/wp/v2/categories" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -d '{
       "name": "새 카테고리",
       "description": "카테고리 설명",
       "slug": "new-category"
     }'

3.4 사용자 관리

# 사용자 목록 (제한적 정보)
curl -X GET "https://yourdomain.com/wp-json/wp/v2/users"

# 현재 사용자 정보 (인증 필요)
curl -X GET "https://yourdomain.com/wp-json/wp/v2/users/me" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

3.5 미디어 관리

# 미디어 목록
curl -X GET "https://yourdomain.com/wp-json/wp/v2/media"

# 미디어 업로드 (인증 필요)
curl -X POST "https://yourdomain.com/wp-json/wp/v2/media" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -F "file=@/path/to/image.jpg" \
     -F "title=이미지 제목" \
     -F "alt_text=대체 텍스트"

4. 인증 방식 완벽 정리

4.1 Cookie 인증 (기본)

WordPress 관리자로 로그인한 상태에서 사용 가능합니다.

// JavaScript에서 사용
fetch('/wp-json/wp/v2/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': wpApiSettings.nonce
  },
  body: JSON.stringify({
    title: '새 글 제목',
    content: '내용'
  })
})

4.2 Application Passwords (권장)

WordPress 5.6 이상에서 사용 가능한 안전한 인증 방식입니다.

설정 방법:

  1. WordPress 관리자 → 사용자 → 프로필
  2. “Application Passwords” 섹션에서 새 비밀번호 생성
  3. 생성된 비밀번호를 HTTP Basic Auth로 사용
curl -X POST "https://yourdomain.com/wp-json/wp/v2/posts" \
     -u "username:application_password" \
     -H "Content-Type: application/json" \
     -d '{
       "title": "새 글",
       "content": "Application Password로 생성된 글"
     }'

4.3 JWT 인증

플러그인 설치:

wp plugin install jwt-authentication-for-wp-rest-api --activate

wp-config.php 설정:

define('JWT_AUTH_SECRET_KEY', 'your-secret-key-here');
define('JWT_AUTH_CORS_ENABLE', true);

토큰 발급:

curl -X POST "https://yourdomain.com/wp-json/jwt-auth/v1/token" \
     -H "Content-Type: application/json" \
     -d '{
       "username": "admin",
       "password": "your_password"
     }'

응답:

{
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
  "user_email": "admin@example.com",
  "user_nicename": "admin",
  "user_display_name": "Admin"
}

토큰 사용:

curl -X GET "https://yourdomain.com/wp-json/wp/v2/posts" \
     -H "Authorization: Bearer YOUR_JWT_TOKEN"

4.4 OAuth 2.0

플러그인 설치:

wp plugin install wp-oauth-server --activate

5. 실전 활용 예제

5.1 JavaScript로 블로그 포스트 가져오기

async function fetchPosts() {
  try {
    const response = await fetch('https://yourdomain.com/wp-json/wp/v2/posts?per_page=10');
    const posts = await response.json();
    
    posts.forEach(post => {
      console.log(`제목: ${post.title.rendered}`);
      console.log(`내용: ${post.content.rendered}`);
      console.log(`작성일: ${new Date(post.date).toLocaleDateString()}`);
      console.log('---');
    });
  } catch (error) {
    console.error('포스트 가져오기 실패:', error);
  }
}

fetchPosts();

5.2 Python으로 게시글 자동 생성

import requests
import json

def create_post(title, content, token):
    url = "https://yourdomain.com/wp-json/wp/v2/posts"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
    data = {
        "title": title,
        "content": content,
        "status": "publish"
    }
    
    response = requests.post(url, headers=headers, data=json.dumps(data))
    
    if response.status_code == 201:
        print("게시글이 성공적으로 생성되었습니다!")
        return response.json()
    else:
        print(f"오류 발생: {response.status_code}")
        return None

# 사용 예제
token = "your_jwt_token_here"
new_post = create_post("자동 생성된 글", "Python으로 생성된 글입니다.", token)

5.3 React 컴포넌트 예제

import React, { useState, useEffect } from 'react';

function WordPressPosts() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchPosts();
  }, []);

  const fetchPosts = async () => {
    try {
      const response = await fetch('https://yourdomain.com/wp-json/wp/v2/posts');
      const data = await response.json();
      setPosts(data);
      setLoading(false);
    } catch (error) {
      console.error('Error fetching posts:', error);
      setLoading(false);
    }
  };

  if (loading) return <div>로딩 중...</div>;

  return (
    <div>
      <h2>최신 포스트</h2>
      {posts.map(post => (
        <article key={post.id}>
          <h3 dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
          <div dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />
          <small>작성일: {new Date(post.date).toLocaleDateString()}</small>
        </article>
      ))}
    </div>
  );
}

export default WordPressPosts;

6. 고급 기능 및 커스터마이징

6.1 커스텀 엔드포인트 생성

// functions.php 또는 플러그인 파일에 추가
function register_custom_endpoints() {
    register_rest_route('custom/v1', '/stats', array(
        'methods' => 'GET',
        'callback' => 'get_site_stats',
        'permission_callback' => '__return_true'
    ));
}

function get_site_stats() {
    $stats = array(
        'total_posts' => wp_count_posts()->publish,
        'total_users' => count_users()['total_users'],
        'total_comments' => wp_count_comments()->approved,
        'wp_version' => get_bloginfo('version')
    );
    
    return new WP_REST_Response($stats, 200);
}

add_action('rest_api_init', 'register_custom_endpoints');

6.2 커스텀 필드 추가

// 커스텀 필드를 REST API 응답에 추가
function add_custom_fields_to_api() {
    register_rest_field('post', 'custom_field', array(
        'get_callback' => function($post) {
            return get_post_meta($post['id'], 'custom_field', true);
        },
        'update_callback' => function($value, $post) {
            return update_post_meta($post->ID, 'custom_field', $value);
        },
        'schema' => array(
            'description' => '커스텀 필드',
            'type' => 'string'
        )
    ));
}

add_action('rest_api_init', 'add_custom_fields_to_api');

6.3 REST API 응답 커스터마이징

// 응답에서 불필요한 필드 제거
function customize_rest_response($response, $post, $request) {
    $data = $response->get_data();
    
    // 필요한 필드만 남기기
    $filtered_data = array(
        'id' => $data['id'],
        'title' => $data['title'],
        'content' => $data['content'],
        'date' => $data['date']
    );
    
    $response->set_data($filtered_data);
    return $response;
}

add_filter('rest_prepare_post', 'customize_rest_response', 10, 3);

7. 보안 및 성능 최적화

7.1 보안 설정

// 특정 사용자만 REST API 접근 허용
function restrict_rest_api_access($result) {
    if (!is_user_logged_in()) {
        return new WP_Error('rest_forbidden', '로그인이 필요합니다.', array('status' => 401));
    }
    return $result;
}

add_filter('rest_authentication_errors', 'restrict_rest_api_access');

7.2 캐싱 설정

// REST API 응답 캐싱
function cache_rest_api_response($response, $server, $request) {
    if ($request->get_method() === 'GET') {
        $response->header('Cache-Control', 'public, max-age=3600');
    }
    return $response;
}

add_filter('rest_post_dispatch', 'cache_rest_api_response', 10, 3);

7.3 Rate Limiting

// 간단한 Rate Limiting 구현
function implement_rate_limiting($result) {
    $ip = $_SERVER['REMOTE_ADDR'];
    $requests = get_transient('api_requests_' . $ip) ?: 0;
    
    if ($requests >= 100) {
        return new WP_Error('rate_limit_exceeded', '요청 한도를 초과했습니다.', array('status' => 429));
    }
    
    set_transient('api_requests_' . $ip, $requests + 1, HOUR_IN_SECONDS);
    return $result;
}

add_filter('rest_authentication_errors', 'implement_rate_limiting');

8. 문제 해결 및 디버깅

8.1 일반적인 오류 및 해결방법

404 오류 (API 엔드포인트를 찾을 수 없음)

# Permalinks 재설정
wp rewrite flush

403 오류 (권한 없음)

  • 인증 토큰 확인
  • 사용자 권한 확인
  • CORS 설정 확인

500 오류 (서버 내부 오류)

// 디버그 모드 활성화 (wp-config.php)
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

8.2 디버깅 도구

// REST API 요청 로깅
function log_rest_api_requests($response, $handler, $request) {
    error_log('REST API Request: ' . $request->get_route());
    error_log('Method: ' . $request->get_method());
    error_log('Parameters: ' . json_encode($request->get_params()));
    return $response;
}

add_filter('rest_request_after_callbacks', 'log_rest_api_requests', 10, 3);

8.3 유용한 플러그인

  • WP REST API Log – API 요청 로깅
  • REST API Enabler/Disabler – API 접근 제어
  • WP REST API Cache – 응답 캐싱

9. 실제 프로젝트 활용 시나리오

9.1 헤드리스 CMS로 활용

// Next.js에서 WordPress를 헤드리스 CMS로 사용
export async function getStaticProps() {
  const res = await fetch('https://yourdomain.com/wp-json/wp/v2/posts');
  const posts = await res.json();

  return {
    props: {
      posts,
    },
    revalidate: 60, // 60초마다 재생성
  };
}

9.2 모바일 앱 연동

// iOS Swift 예제
struct Post: Codable {
    let id: Int
    let title: Title
    let content: Content
}

struct Title: Codable {
    let rendered: String
}

struct Content: Codable {
    let rendered: String
}

func fetchPosts() {
    guard let url = URL(string: "https://yourdomain.com/wp-json/wp/v2/posts") else { return }
    
    URLSession.shared.dataTask(with: url) { data, response, error in
        if let data = data {
            do {
                let posts = try JSONDecoder().decode([Post].self, from: data)
                DispatchQueue.main.async {
                    // UI 업데이트
                }
            } catch {
                print("JSON 디코딩 오류: \(error)")
            }
        }
    }.resume()
}

10. 결론

WordPress REST API는 현대적인 웹 개발에서 WordPress를 더욱 유연하고 강력하게 활용할 수 있게 해주는 핵심 기능입니다. 이 가이드를 통해 다음을 학습했습니다:

기본 개념과 설정 방법핵심 엔드포인트 사용법다양한 인증 방식실전 활용 예제보안 및 성능 최적화

다음 단계

  1. 실제 프로젝트에 적용해보기
  2. 커스텀 엔드포인트 개발
  3. 보안 강화 및 성능 최적화
  4. 외부 서비스와의 연동

WordPress REST API를 마스터하면 WordPress를 단순한 CMS를 넘어 현대적인 웹 애플리케이션의 강력한 백엔드로 활용할 수 있습니다.


🔗 유용한 리소스




댓글 남기기