API(Application Programming Interface)는 현대 개발에서 없어서는 안 될 중요한 개념인건 다들 알고 있을 것이다.
하지만 처음 공부를 시작하면 생소한 용어, 비동기 작업, 네트워크 구조 등 많은 장애물에 부딪히기 마련이고,
나 또한 API를 배우는 과정이지만 많은 어려움을 느끼고 현재도 마냥 쉽지는 않다.
그래서 비슷한 어려움을 겪는 사람들을 위해 그저 작성한 것일 뿐이니 편하게 봐줬으면 한다.
추상적인 개념
기초 지식 부족
비동기 작업의 복잡성
단계별 접근의 부족
작은 목표부터 시작해보자
처음부터 복잡한 API를 다루지 말고, 간단한 JSON 데이터를 가져오는 예제부터 시작하는 거다.
https://jsonplaceholder.typicode.com/posts
는 실제 데이터가 아니라 테스트를 위해 제공되는 샘플 API이다.
JSONPlaceholder는 가상 데이터를 제공하는데 그 곳에서 가져온 데이터는 서버에 저장되지 않는다.
따라서 데이터를 POST 요청으로 추가하거나 수정하더라도 다시 요청하면 초기 상태로 돌아온다.
예를 들면 이 URL로 GET 요청을 보내면 아래와 같은 데이터가 반환되어야 한다.
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
// 아래에 더 많은 항목이 있다
]
Postman 또는 cURL 사용
브라우저로 확인
Swift로 호출해보자
먼저 위에 데이터를 Swift 구조체로 변환하기 위해 아래와 같이 정의해보자.
struct Post: Codable {
let userId: Int
let id: Int
let title: String
let body: String
}
그리고 URLSession
을 사용해 데이터를 가져오는 간단한 예제를 작성해보는 것이다.
import Foundation
class APIService {
func fetchPosts(completion: @escaping (Result<[Post], Error>) -> Void) {
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
let error = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data received"])
completion(.failure(error))
return
}
do {
let posts = try JSONDecoder().decode([Post].self, from: data)
completion(.success(posts))
} catch {
completion(.failure(error))
}
}
task.resume()
}
}
기본을 이해하자
단계를 나눠보자
API를 다루는 과정을 다음과 같이 단계별로 연습하는 것이다.
디버깅을 두려워하지 말자..!
Swift로 비동기 작업 연습하기
URLSession
을 사용하여 API 요청을 보내고 데이터를 처리하는 코드를 작성해보자.Alamofire
나 Moya
같은 라이브러리를 사용해 작업을 더 효율적으로 처리할 수 있다.API 공부는 처음에는 어렵지만, 한 단계씩 나아가다 보면 어느새 익숙해질 것이라고 생각한다.
나도 처음에는 너무 어려워서.. 공부하기 싫어했던 적이 있었는데, 하나씩 연습해보면 어느새 점점 눈에 보이기 시작한다.
천천히, 그리고 꾸준히. 완벽하지 않아도 괜찮다.
차근차근 공부하는 모습이 멋져요