Swiftpack.co - RxDx/restapi as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by RxDx.
RxDx/restapi 1.0.1
RestApi
⭐️ 3
🕓 5 days ago
iOS macOS
.package(url: "https://github.com/RxDx/restapi.git", from: "1.0.1")

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](https://raw.github.com/RxDx/restapi/main/)
    @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

GitHub

link
Stars: 3
Last commit: 5 days ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics