0Pricing
Flutter Mobile Development · 강의

HTTP 요청 및 JSON

REST API에 HTTP GET, POST, PUT 및 DELETE 요청을 보내고 JSON 응답을 Dart 객체로 분석하는 방법을 학습합니다.

HTTP 요청 및 JSON은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Connect to the Web!

Modern mobile apps constantly interact with the internet to fetch and send data. This is often done using HTTP requests to communicate with web services, also known as APIs (Application Programming Interfaces).

APIs provide a way for different software systems to talk to each other. For example, a weather app uses an API to get the latest forecast.

Get the `http` Package

In Flutter and Dart, the easiest way to make HTTP requests is by using the official http package. First, you need to add it to your project's pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.2.0 # Add this line

Making a GET Request

After adding the package, import it into your Dart file. The most common request is GET, used to retrieve data from a server. Let's fetch some dummy post data from a public API:

import 'package:http/http.dart' as http;
import 'dart:convert'; // Needed for JSON

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);

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

What is JSON?

Most web APIs return data in JSON (JavaScript Object Notation) format. It's a lightweight, human-readable way to organize data.

JSON data looks like key-value pairs, similar to Dart maps. Here's what our previous GET request might return:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere...",
  "body": "quia et suscipit..."
}

Parsing JSON to Dart

To work with JSON data in Dart, we need to decode it. Dart's dart:convert library provides the jsonDecode() function, which converts a JSON string into a Dart Map.

Let's update our GET example to parse the response:

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

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);

  if (response.statusCode == 200) {
    var jsonBody = jsonDecode(response.body);
    print('User ID: ${jsonBody['userId']}');
    print('Title: ${jsonBody['title']}');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

Structured Data with Models

While using Map is okay for simple cases, creating a dedicated Dart model class for your JSON data offers better type safety and code readability.

A common pattern is to have a factory constructor that takes a JSON map and creates an instance of your model.

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({required this.userId, required this.id, required this.title, required this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }
}

Fetching Data into a Model

Now, let's combine our GET request, JSON decoding, and the Post model to fetch a post and convert it into a strongly-typed Dart object. This makes accessing data much safer and clearer!

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

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({required this.userId, required this.id, required this.title, required this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }
}

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);

  if (response.statusCode == 200) {
    var jsonBody = jsonDecode(response.body);
    Post post = Post.fromJson(jsonBody);
    print('Fetched Post ID: ${post.id}');
    print('Post Title: ${post.title}');
  } else {
    print('Failed to load post: ${response.statusCode}.');
  }
}

Sending Data with POST

To send new data to a server, you typically use a POST request. This involves providing a request body, usually in JSON format. Remember to set the 'Content-Type' header!

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

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
  var response = await http.post(
    url,
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': 'foo',
      'body': 'bar',
      'userId': '1',
    }),
  );

  if (response.statusCode == 201) { // 201 Created
    print('Created Post: ${response.body}');
  } else {
    print('Failed to create post: ${response.statusCode}.');
  }
}

Updating & Deleting Data

Besides GET and POST, you'll also encounter PUT and DELETE requests:

  • PUT: Used to update an existing resource on the server. Similar to POST, it typically includes a request body.
  • DELETE: Used to remove a resource from the server. It usually doesn't require a request body.

The http package provides http.put() and http.delete() functions, used similarly to http.post() and http.get() respectively.

Robust Request Handling

Network requests can fail for many reasons (no internet, server down, invalid data). Always prepare for these scenarios:

  • Use try-catch for network-related exceptions (e.g., SocketException).
  • Check response.statusCode to understand the server's reply (e.g., 200 OK, 404 Not Found, 500 Server Error).

This ensures your app remains stable even when things go wrong.

HTTP Request Check

Which HTTP method(s) are typically used to send new data to a server and retrieve existing data from a server, respectively?

Recap: HTTP & JSON

Great job! You've learned the fundamentals of making HTTP requests and handling JSON data:

  • The http package is essential for network calls.
  • GET retrieves data, POST sends new data, PUT updates, and DELETE removes data.
  • JSON is the standard format for API data.
  • Use dart:convert to jsonDecode responses and jsonEncode request bodies.
  • Dart model classes improve type safety and organization.

Next, you'll dive deeper into handling errors robustly in asynchronous operations!

자주 묻는 질문

“HTTP 요청 및 JSON” 강의는 무료인가요?

네 — “HTTP 요청 및 JSON” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“HTTP 요청 및 JSON”에서 뭘 배우나요?

REST API에 HTTP GET, POST, PUT 및 DELETE 요청을 보내고 JSON 응답을 Dart 객체로 분석하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“HTTP 요청 및 JSON” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Future 및 비동기 대기
  2. HTTP 요청 및 JSON
  3. 비동기 작업의 오류 처리
  4. Stream과 반응형 데이터
← Flutter Mobile Development(으)로 돌아가기