RestApi

1.2.0

RestApi
RxDx/restapi

What's New

RestApi

Simple and lightweight swift async rest implementation.

Installation

Swift Package Manager

Usage

  • Instantiate your service
  • Start making rest calls!

Simple usage

let service = RestApi(baseUrl: "https://url.com/resources")

Complete usage

let service = RestApi(
    baseUrl: "https://url.com",
    path: "resources",
    header: [
        "Content-Type": "application/json; charset=utf-8",
        "Accept": "application/json; charset=utf-8"
    ],
    debug: false,
    urlSession: URLSession.shared
)

Rest Calls

let resources: [Resource] = try await service.get()
let resource: Resource = try await service.get(resourceId: "id")
let newResource: Resource? = try await service.post(resource: Resource())
let updatedResource: Resource? = try await service.put(resourceId: "id", resource: Resource())
let updatedResource: Resource? = try await service.patch(resourceId: "id", payload: ["key": "value"])
try await service.delete(resourceId: "id")

Example

SwiftUI View Example:

import SwiftUI
import RestApi

struct Post: Codable, Hashable, Identifiable {
    let id: Int
    let userId: Int
    let title: String
    let body: String
}

class PostsViewModel: ObservableObject {
    private let service = RestApi(baseUrl: "https://jsonplaceholder.typicode.com", path: "posts")
    @Published private(set) var posts = [Post]()
    @MainActor func getPosts() async {
        do {
            self.posts = try await service.get()
        } catch {
            debugPrint(error.localizedDescription)
        }
    }
}

struct PostsView: View {
    @ObservedObject private var viewModel = PostsViewModel()
    var body: some View {
        List(viewModel.posts, id: \.id) { post in
            NavigationLink {
                PostView(postId: post.id)
            } label: {
                Text(post.title)
            }
        }
        .navigationTitle("Posts")
        .task {
            await viewModel.getPosts()
        }
    }
}

Running Tests

To run tests, go to Product -> Test, or run the following shortcut

  cmd + U

Description

  • Swift Tools 5.6.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sat Mar 16 2024 13:08:11 GMT-0900 (Hawaii-Aleutian Daylight Time)