Swiftpack.co - DominatorVbN/ElegantAPI as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by DominatorVbN.
DominatorVbN/ElegantAPI 1.0.1
A api management API inspired from moya but for URLSession
⭐️ 22
🕓 51 weeks ago
.package(url: "https://github.com/DominatorVbN/ElegantAPI.git", from: "1.0.1")

ElegantAPI

Swift Package Manager compatible Build

An URSessionDataTaskPublisher abstraction layer inspired by Moya.

Documentation

https://amitsamant.in/ElegantAPI/documentation/elegantapi/

Installation

Elegant api is available through Swift Package Manager

add this url to File -> Swift Packages -> Add new Dependecy

https://github.com/DominatorVbN/ElegantAPI.git

or

add the following as a dependency to your Package.swift:

.package(url: "https://github.com/DominatorVbN/ElegantAPI.git", .upToNextMajor(from: "0.0.9"))

Usage

import ElegentAPI

import ElegantAPI

You have to declare an enum representing your api endpoints

enum APIEndpoint{
    case login(emailId: String, password: String)
    case getProfile
    case updateProfile(user: User)
    case changeProfileImage(profileImage: UIImage)
}

Implement the enum with protocol API which contains all the requirement

extension APIEndpoint: API{

    var baseURL: URL {
        // You can provide diffrent base urls for diffrent endpoint enum cases
        URL(string: "<Your base URL>")!
    }
    
    // End point path
    var path: String {
    
        switch self {
        case login:
            return "login"
        case getProfile:
            return "get_profile"
        case updateProfile:
            return "update_profile"
        case changeProfileImage:
            return change_profile_image
        }
        
    }
    
    // HTTP method of endpoint
    var method: ElegantAPI.Method {
    
        switch self {
        case .login:
            return .post
        case .getProfile:
            return .get
        case .updateProfile:
            return .patch
        case changeProfileImage:
            return .put
        }
        
    }
    
    var sampleData: Data {
        // for mocking requests
        Data()
    }
    
    var task: Task {
        switch self {
        
        case .login(let email,let password):
            return .requestParameters(parameters: [
                "email": email,
                "password": password
            ], encoding: .JSONEncoded)
            
        case .getProfile:
            return .requestPlain
            
        case .updateProfile(let user):
            return .requestJSONEncodable(user)
            
        case .changeProfileImage(let image):
            var data: [MultipartFormData] = [
                MultipartFormData(
                    data: image.jpegData(compressionQuality: 0.4) ?? Data(),
                    name: "image",
                    fileName: "\(UUID().uuidString).png",
                    mimeType: "image/jpeg"
                )
            ]
            return .uploadMultipart(data)
            
        }
    }
    
    // Headers for request
    var headers: [String : String]? {
    
        switch self {
        case .login:
            return ["Content-Type": "application/json"]
        case .getProfile, .updateProfile, .changeProfileImage:
            return ["Authorization": "Bearer \(Persistance.shared.accessKey)"]
        }
        
    }
    
}

And that's you can define all api requests Now to perform this request

Using Combine


guard let request = APIEndpoint.login.getURLRequest() else {return}

// NetworkLogger is an micro library included inside Elegant api for logging network response and requests
NetworkLogger.log(request: request)

let publisher = URLSession.shared.dataTaskPublisher(for: req)

publisher.map { output in
    NetworkLogger.log(data: output.data, response: output.response as? HTTPURLResponse, error: nil)
    return output
}.sink(
    receiveCompletion: { },
    receiveValue: { output in
        print(output.data)
    }
)

You can also you the URLRequest for plain dataTask too.

GitHub

link
Stars: 22
Last commit: 21 weeks ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

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