Code Monkey home page Code Monkey logo

apikit's Introduction

ApiKit

Platform

A simple way to connect your swift code to your APIs.

iOS 12+

Api.send(.get("https://jsonplaceholder.typicode.com/users")) { (result: Result<[User], Error>) in
    switch result {
        case let .success(users):
            break
        case let .failure(error):
            break
    }
}

iOS 13+

let users: [User] = try await Api.send(.get("https://jsonplaceholder.typicode.com/users"))

Why?

Allows for simple middleware/intercepting of request and response. Which is great for custom authentication / request & response manipulation. Also since it just wraps Apple's URLSession API it is very easy to intergrate into existing codebases.

Advanced Usage

ProductionEndpoints.swift Production Target

private let mobileEndpoints = StaticEndpointInfo(url: "https://...")

StagingEndpoints.swift Staging Target

private let mobileEndpoints = StaticEndpointInfo(url: "https://staging...")

Api.swift

class MyApi: Api {
  private var mobileServices: EndpointInfo = mobileEndpoints

  init() {
    let config = DefaultApiConfig(interceptors: [LogInterceptor(level: .verbose)])
    super.init(urlSession: URLSession.shared, config: config)
  }
}

extension MyApi: UserResource {
  @discardableResult
  func getAllUsers(completion: ApiCompletion<[User]>) -> HttpOperation? {
    return send(.get(endpoint: mobileServices, path: "/users"),
                completion: completion)
  }

  @discardableResult
  func createUser(user: CreateUser, completion: ApiCompletion<User>) -> HttpOperation? {
    return send(try! .post(endpoint: mobileServices, path: "/users", body: user),
                completion: completion)
  }
}

EndpointInfo

This saves you from having to repeat your base url and default headers that need to be on all requests like API keys.

private let mobileEndpoints = StaticEndpointInfo(url: "https://...", headers: ["API-Key": "..."])

Interception

Included Inceptors

  • ChaosInterceptor used to cause chaos. THIS SHOULD ONLY BE USED WHEN DEBUG IS ENABLED AKA #if DEBUG
  • LogInterceptor used to add logging to all request and response.
  • OAuthInterceptor used to add OAuth authentication to an API using an OAuthProvider.

Creating a custom interceptor allows you modify every request or response, or a specific request and response.

Example of a inceptor that looks for bad status code and decodes a generic error response body.

struct MyApiError {
    var code: Int
    var message: String
}

class ErrorInterceptor: ApiInterceptor {
    func api(_ api: Api,
           didReceive result: Result<HttpDataResponse, Error>,
           withId identifier: UUID,
           for request: URLRequest,
           completion: HttpDataCompletion) -> Bool
    {
        if let .success(response) = result { 
            if !response.successful {
                let apiError = api.config.decoder.decode(MyApiError.self, response.data)
                completion(.failure(ApiError.badStatusCode(error: apiError, response: response)))
                return true
            }
        }
        return false
    }
}

let api = Api(config: DefaultApiConfig(interceptors: [ErrorInterceptor()]))
api.send(.get("https://....")) { (result: Result<[User], Error>) in
    switch (result) {
        case let .failure(error):
            if let Api
    }
}

apikit's People

Contributors

nicholasmata avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.