📁 [4] 개발자 정보 & 코드 노트/C#

C# Windows Forms 강의 97편: REST API와 연동하여 실시간 데이터 가져오기

wawManager 2025. 5. 11. 12:00
반응형

 

1. 강의 개요

이번 강의에서는 REST API와 연동하여 실시간 데이터를 가져오고 처리하는 애플리케이션을 제작합니다.
REST API는 웹 서비스와 데이터를 교환하기 위해 널리 사용되는 프로토콜로,
이 강의에서는 C#의 HttpClient 클래스를 활용하여 데이터를 요청하고
JSON 데이터를 처리하는 방법을 학습합니다.


2. 학습 목표

  • HttpClient를 사용한 REST API 요청 및 응답 처리
  • JSON 데이터를 파싱하여 DataGridView에 표시
  • 실시간 데이터 요청을 위한 버튼 UI 구성
  • 비동기 프로그래밍(Async/Await)을 사용하여 UI 응답성 유지

3. 기능 요구사항

필수 기능

1️⃣ API 데이터 가져오기:

  • REST API를 통해 데이터를 가져와 JSON 형태로 처리

2️⃣ JSON 데이터 시각화:

  • JSON 데이터를 DataGridView에 표시

3️⃣ 실시간 요청 버튼 구성:

  • 버튼 클릭 시 데이터 요청 및 갱신

4. 실습: REST API 연동 애플리케이션 제작

1️⃣ 폼 구성

  • 폼(Form) 이름: Form1
  • 컨트롤 배치:

컨트롤 타입 이름 위치 크기

Button btnFetch 폼 상단 왼쪽 (100 x 30)
DataGridView dgvData 폼 상단 오른쪽 (600 x 300)

📌 폼 디자인 예시:

--------------------------------------------------
| [Fetch 버튼]                      [DataGridView] |
--------------------------------------------------

2️⃣ 코드 작성

(1) API 데이터 가져오기

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace WindowsFormsApp_RESTAPI
{
    public partial class Form1 : Form
    {
        private const string ApiUrl = "https://jsonplaceholder.typicode.com/posts"; // 테스트용 API

        public Form1()
        {
            InitializeComponent();
        }

        // 데이터 가져오기 버튼
        private async void btnFetch_Click(object sender, EventArgs e)
        {
            try
            {
                var data = await FetchDataAsync();
                PopulateDataGridView(data);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"데이터를 가져오는 중 오류가 발생했습니다: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 비동기로 API 데이터 요청
        private async Task<list> FetchDataAsync()
        {
            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetStringAsync(ApiUrl);
                return JsonConvert.DeserializeObject<list>(response);
            }
        }

        // DataGridView에 데이터 바인딩
        private void PopulateDataGridView(List data)
        {
            dgvData.DataSource = data;
        }

        // Post 데이터 모델 클래스
        public class Post
        {
            public int UserId { get; set; }
            public int Id { get; set; }
            public string Title { get; set; }
            public string Body { get; set; }
        }
    }
}
</list</list

(2) Designer 코드

        private void InitializeComponent()
        {
            this.btnFetch = new Button();
            this.dgvData = new DataGridView();

            // Fetch Button 설정
            this.btnFetch.Location = new System.Drawing.Point(10, 10);
            this.btnFetch.Size = new System.Drawing.Size(100, 30);
            this.btnFetch.Text = "Fetch";
            this.btnFetch.Click += new EventHandler(this.btnFetch_Click);

            // DataGridView 설정
            this.dgvData.Location = new System.Drawing.Point(120, 10);
            this.dgvData.Size = new System.Drawing.Size(600, 300);

            // Form 설정
            this.ClientSize = new System.Drawing.Size(750, 350);
            this.Controls.Add(this.btnFetch);
            this.Controls.Add(this.dgvData);
            this.Text = "REST API 연동";
        }

3️⃣ 실행 결과

1️⃣ 데이터 가져오기

  • "Fetch" 버튼 클릭 → API에서 데이터를 가져와 DataGridView에 표시

2️⃣ JSON 데이터 시각화

  • JSON 데이터를 C# 객체로 변환하여 DataGridView에 표시

5. 주요 개념 요약

  • HttpClient: REST API와의 HTTP 요청 및 응답 처리
  • Async/Await: 비동기 프로그래밍을 통해 UI 응답성을 유지
  • JsonConvert.DeserializeObject: JSON 데이터를 C# 객체로 역직렬화
  • DataGridView: 데이터를 시각적으로 관리

 

📌 #CSharp #WindowsForms #RESTAPI #HttpClient #JSON #DataGridView

반응형