이 포스팅은 Flutter 3.24 버전 기준으로 작성되었습니다.
dart pub add json_annotation dio retrofit
dart pub add --dev build_runner retrofit_generator json_serializable
dependencies:
retrofit: ^4.4.2
dio: ^5.7.0
json_annotation: ^4.9.0
dev_dependencies:
build_runner: ^2.4.13
retrofit_generator: ^9.1.5
json_serializable: ^6.9.0
https://jsonplaceholder.typicode.com/users
API를 호출하면 아래와 같은 응답을 받을 수 있습니다.[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
// ...
]
import 'package:json_annotation/json_annotation.dart';
part 'user_dto.g.dart';
@JsonSerializable()
class UserDto {
final int id;
final String name;
final String username;
final String email;
final Address address;
final String phone;
final String website;
final Company company;
UserDto({
required this.id,
required this.name,
required this.username,
required this.email,
required this.address,
required this.phone,
required this.website,
required this.company,
});
factory UserDto.fromJson(Map<String, dynamic> json) => _$UserDtoFromJson(json);
Map<String, dynamic> toJson() => _$UserDtoToJson(this);
}
@JsonSerializable()
class Address {
final String street;
final String suite;
final String city;
final String zipcode;
final Geo geo;
Address({
required this.street,
required this.suite,
required this.city,
required this.zipcode,
required this.geo,
});
factory Address.fromJson(Map<String, dynamic> json) => _$AddressFromJson(json);
Map<String, dynamic> toJson() => _$AddressToJson(this);
}
@JsonSerializable()
class Geo {
final String lat;
final String lng;
Geo({
required this.lat,
required this.lng,
});
factory Geo.fromJson(Map<String, dynamic> json) => _$GeoFromJson(json);
Map<String, dynamic> toJson() => _$GeoToJson(this);
}
@JsonSerializable()
class Company {
final String name;
final String catchPhrase;
final String bs;
Company({
required this.name,
required this.catchPhrase,
required this.bs,
});
factory Company.fromJson(Map<String, dynamic> json) => _$CompanyFromJson(json);
Map<String, dynamic> toJson() => _$CompanyToJson(this);
}
import 'package:dio/dio.dart';
import 'package:retrofit/retrofit.dart';
import 'user_dto.dart';
part 'user.g.dart'; // 생성될 파일
@RestApi(baseUrl: "https://jsonplaceholder.typicode.com") // base url
abstract class UserApi {
factory UserApi(Dio dio, {String baseUrl}) = _UserApi;
@GET("/users") // 요청할 API
Future<List<UserDto>> getUsers(); // 요청할 API의 응답을 받을 모델 클래스
}
dart run build_runner build
lib/model/user_dto.g.dart
lib/model/user.g.dart
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:retrofit/retrofit.dart';
import 'package:{project명}/model/user/user.dart'; // 작성한 프로젝트의 경로에 맞게 수정해주세요.
void runApiExample() {
final dio = Dio();
final client = GetUserApi(dio);
client.getUsers().then((userList) => {
for (final user in userList) {log(user.toJson().toString())}
});
}
[log] {id: 1, name: Leanne Graham, username: Bret, email: Sincere@april.biz, address: Instance of 'Address', phone: 1-770-736-8031 x56442, website: hildegard.org, company: Instance of 'Company'}
[log] {id: 2, name: Ervin Howell, username: Antonette, email: Shanna@melissa.tv, address: Instance of 'Address', phone: 010-692-6593 x09125, website: anastasia.net, company: Instance of 'Company'}
[log] {id: 3, name: Clementine Bauch, username: Samantha, email: Nathan@yesenia.net, address: Instance of 'Address', phone: 1-463-123-4447, website: ramiro.info, company: Instance of 'Company'}
[log] {id: 4, name: Patricia Lebsack, username: Karianne, email: Julianne.OConner@kory.org, address: Instance of 'Address', phone: 493-170-9623 x156, website: kale.biz, company: Instance of 'Company'}
[log] {id: 5, name: Chelsey Dietrich, username: Kamren, email: Lucio_Hettinger@annie.ca, address: Instance of 'Address', phone: (254)954-1289, website: demarco.info, company: Instance of 'Company'}
[log] {id: 6, name: Mrs. Dennis Schulist, username: Leopoldo_Corkery, email: Karley_Dach@jasper.info, address: Instance of 'Address', phone: 1-477-935-8478 x6430, website: ola.org, company: Instance of 'Company'}
[log] {id: 7, name: Kurtis Weissnat, username: Elwyn.Skiles, email: Telly.Hoeger@billy.biz, address: Instance of 'Address', phone: 210.067.6132, website: elvis.io, company: Instance of 'Company'}
[log] {id: 8, name: Nicholas Runolfsdottir V, username: Maxime_Nienow, email: Sherwood@rosamond.me, address: Instance of 'Address', phone: 586.493.6943 x140, website: jacynthe.com, company: Instance of 'Company'}
[log] {id: 9, name: Glenna Reichert, username: Delphine, email: Chaim_McDermott@dana.io, address: Instance of 'Address', phone: (775)976-6794 x41206, website: conrad.com, company: Instance of 'Company'}
[log] {id: 10, name: Clementina DuBuque, username: Moriah.Stanton, email: Rey.Padberg@karina.biz, address: Instance of 'Address', phone: 024-648-3804, website: ambrose.net, company: Instance of 'Company'}
@GET('/users/{id}')
Future<UserDto> getUserByPathId(@Path() int id); // 파라미터 전달
@GET('/users')
Future<List<UserDto>> getUserByQueryId(
@Query('id') int id,
); // 쿼리 파라미터 전달
@GET('/users')
@Headers(<String, dynamic>{
'Content-Type': 'application/json',
'Authorization': 'Bearer {token}',
})
Future<List<UserDto>> getUsers(); // 헤더 전달
@GET('/users')
Future<List<UserDto>> getUsers(
@Header('Content-Type') String content_type,
@Header('Authorization') String authorization,
); // 헤더 전달
@POST('/users')
Future<UserDto> createUser(@Body() UserDto user); // 바디 전달
rm lib/model/user/user.g.dart
dart run build_runner build