본문 바로가기
Dart/Dart Server

[초급] Dart Server JSON 처리 및 데이터 직렬화/ 간단한 API 서버 구축하기: JSON 데이터 반환 및 처리

by Maccrey Coding 2024. 9. 6.
반응형

 

Dart는 서버 개발에도 강력한 기능을 제공하며, 특히 dart:io와 dart:convert 라이브러리를 사용하여 간단한 API 서버를 구축할 수 있습니다.

이 블로그에서는 Dart로 JSON 데이터를 반환하고 처리하는 간단한 API 서버를 구축하는 방법을 초보자도 쉽게 이해할 수 있도록 설명하겠습니다.

1. 환경 설정

먼저, Dart SDK를 설치하고 개발 환경을 설정해야 합니다. Dart SDK가 설치된 후, 원하는 IDE(예: Visual Studio Code, IntelliJ)에서 Dart 프로젝트를 생성합니다.

2. 간단한 HTTP 서버 구축

Dart에서 HTTP 서버를 구축하려면 dart:io 라이브러리를 사용합니다. 이 라이브러리는 HTTP 요청과 응답을 처리하는 데 필요한 기능을 제공합니다.

2.1 기본적인 HTTP 서버

다음 예제는 Dart로 기본적인 HTTP 서버를 구축하는 방법을 보여줍니다.

import 'dart:io';

void main() async {
  // 서버를 'localhost'의 포트 8080에서 시작합니다.
  var server = await HttpServer.bind('localhost', 8080);
  print('Server listening on port 8080');

  await for (HttpRequest request in server) {
    // 응답 작성
    request.response
      ..write('Hello, World!')
      ..close();
  }
}

이 서버는 포트 8080에서 HTTP 요청을 수신하고, 모든 요청에 대해 "Hello, World!"라는 텍스트를 반환합니다.

3. JSON 데이터 반환

API 서버에서 JSON 데이터를 반환하려면 dart:convert 라이브러리의 jsonEncode 함수를 사용하여 Dart 객체를 JSON 문자열로 변환합니다.

3.1 JSON 데이터 반환 예제

import 'dart:convert';
import 'dart:io';

void main() async {
  // 서버를 'localhost'의 포트 8080에서 시작합니다.
  var server = await HttpServer.bind('localhost', 8080);
  print('Server listening on port 8080');

  await for (HttpRequest request in server) {
    if (request.uri.path == '/api/user' && request.method == 'GET') {
      // 반환할 JSON 데이터
      var responseData = {'name': 'John', 'age': 30};

      // JSON 데이터 반환
      request.response
        ..headers.contentType = ContentType.json
        ..write(jsonEncode(responseData))
        ..close();
    } else {
      request.response
        ..statusCode = HttpStatus.notFound
        ..write('Not Found')
        ..close();
    }
  }
}

이 서버는 /api/user 경로로 GET 요청을 받으면 JSON 데이터를 반환합니다.

ContentType.json 헤더를 설정하여 응답이 JSON 형식임을 명시하고, jsonEncode를 사용하여 Dart 객체를 JSON 문자열로 변환하여 반환합니다.

4. JSON 데이터 처리

POST 요청으로 JSON 데이터를 서버에 보내고 처리하는 방법을 알아보겠습니다. 클라이언트가 서버에 JSON 데이터를 보내면, 서버는 이를 읽고 적절히 처리한 후 응답을 반환합니다.

4.1 JSON 데이터 처리 예제

import 'dart:convert';
import 'dart:io';

void main() async {
  // 서버를 'localhost'의 포트 8080에서 시작합니다.
  var server = await HttpServer.bind('localhost', 8080);
  print('Server listening on port 8080');

  await for (HttpRequest request in server) {
    if (request.uri.path == '/api/user' && request.method == 'POST') {
      // 요청 본문 읽기
      var content = await utf8.decoder.bind(request).join();
      var requestData = jsonDecode(content);

      // 요청 데이터를 처리
      var responseData = {'received': requestData};

      // JSON 응답 반환
      request.response
        ..headers.contentType = ContentType.json
        ..write(jsonEncode(responseData))
        ..close();
    } else {
      request.response
        ..statusCode = HttpStatus.notFound
        ..write('Not Found')
        ..close();
    }
  }
}

이 서버는 /api/user 경로로 POST 요청을 받으면, 요청 본문에서 JSON 데이터를 읽고, 이를 jsonDecode를 사용하여 Dart 객체로 변환합니다.

변환된 데이터는 responseData 객체에 포함되어 JSON 형태로 응답됩니다.

5. 클라이언트에서 API 서버에 요청하기

API 서버에 요청을 보내는 클라이언트를 Dart로 작성할 수 있습니다. 다음 예제는 HTTP 클라이언트를 사용하여 서버에 GET과 POST 요청을 보내는 방법을 보여줍니다.

5.1 GET 요청 보내기

import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  // 서버 URL
  var url = Uri.parse('http://localhost:8080/api/user');

  // GET 요청 보내기
  var response = await http.get(url);

  if (response.statusCode == 200) {
    var data = jsonDecode(response.body);
    print('Received data: $data');
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

5.2 POST 요청 보내기

import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  // 서버 URL
  var url = Uri.parse('http://localhost:8080/api/user');

  // Dart 객체
  var user = {'name': 'John', 'age': 30};

  // JSON 문자열로 변환
  var jsonString = jsonEncode(user);

  // POST 요청 보내기
  var response = await http.post(
    url,
    headers: {'Content-Type': 'application/json'},
    body: jsonString,
  );

  if (response.statusCode == 200) {
    var data = jsonDecode(response.body);
    print('Received response: $data');
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

 

Dart를 사용하여 JSON 데이터를 반환하고 처리하는 간단한 API 서버를 구축하는 방법을 알아보았습니다.

HTTP 서버와 클라이언트에서 JSON 데이터를 처리하는 기초적인 방법을 이해하고 나면, 더 복잡한 데이터 처리와 API 통신을 구현할 수 있는 토대를 마련할 수 있습니다.

Dart의 dart:io와 dart:convert 라이브러리를 활용하여 강력한 서버와 클라이언트를 만들어 보세요.

구독!! 공감과 댓글은 저에게 큰 힘이 됩니다.

Starting Google Play App Distribution! "Tester Share" for Recruiting 20 Testers for a Closed Test.

 

Tester Share [테스터쉐어] - Google Play 앱

Tester Share로 Google Play 앱 등록을 단순화하세요.

play.google.com

 

반응형