Saturday, October 14, 2023
HomeiOS DevelopmentAsync HTTP API shoppers in Swift

Async HTTP API shoppers in Swift


Introducing SwiftHttp

An superior Swift HTTP library to quickly create communication layers with API endpoints. The library tries to separate the shopper request logic from the request constructing and response dealing with. That is the principle cause why it has a HttpClient protocol which can be utilized to carry out knowledge, obtain and add duties. You possibly can implement your individual HttpClient, however SwiftHttp comes with a built-in UrlSessionHttpClient based mostly on Basis networking.


So the shopper is chargeable for executing the requests, however we nonetheless have to explain the request itself one way or the other. That is the place the HttpRawRequest object comes into play. You possibly can simply create a base HttpUrl and carry out a request utilizing the HttpRawRequest object. When working with a uncooked request you’ll be able to specify extra header fields and a uncooked physique knowledge object too. 💪


let url = HttpUrl(scheme: "https",
                  host: "jsonplaceholder.typicode.com",
                  port: 80,
                  path: ["todos"],
                  useful resource: nil,
                  question: [:],
                  fragment: nil)

let req = HttpRawRequest(url: url, technique: .get, headers: [:], physique: nil)


let shopper = UrlSessionHttpClient(session: .shared, log: true)
let response = attempt await shopper.dataTask(req)


let todos = attempt JSONDecoder().decode([Todo].self, from: response.knowledge)


The HTTP shopper can carry out community calls utilizing the brand new async / await Swift concurrency API. It’s potential to cancel a community request by wrapping it right into a structured concurrency Activity.


let job = Activity {
    let api = TodoApi()
    _ = attempt await api.checklist()
}

DispatchQueue.world().asyncAfter(deadline: .now() + .milliseconds(10)) {
    job.cancel()
}

do {
    let _ = attempt await job.worth
}
catch {
    if (error as? URLError)?.code == .cancelled {
        print("cancelled")
    }
}


It is a neat tick, you may also examine the rationale contained in the catch block, whether it is an URLError with a .cancelled code then the request was cancelled, in any other case it have to be some type of community error.


So that is how you should utilize the shopper to carry out or cancel a community job, however normally you do not need to work with uncooked knowledge, however encodable and decodable objects. While you work with such objects, you may need to validate the response headers and ship extra headers to tell the server about the kind of the physique knowledge. Simply take into consideration the Content material-Sort / Settle for header fields. 🤔


So we’d need to ship extra headers alongside the request, plus it would be good to validate the standing code and response headers earlier than we attempt to parse the info. This looks as if a move of widespread operations, first we encode the info, set the extra header fields, and when the response arrives we validate the standing code and the header fields, lastly we attempt to decode the info object. It is a typical use case and SwiftHttp calls this workflow as a pipeline.


There are 4 kinds of built-in HTTP pipelines:


  • Uncooked – Ship a uncooked knowledge request, return a uncooked knowledge response
  • Encodable – Ship an encodable object, return a uncooked knowledge response
  • Decodable – Ship a uncooked knowledge request, return a decodable object
  • Codable – Ship an encodable object, return a decodable object


We will use a HttpRawPipeline and execute our request utilizing a shopper as an executor.


let baseUrl = HttpUrl(host: "jsonplaceholder.typicode.com")
let shopper = UrlSessionHttpClient(session: .shared, log: true)

let pipeline = HttpRawPipeline(url: baseUrl.path("todos"), technique: .get)

let response = attempt await pipeline.execute(shopper.dataTask)
let todos = attempt JSONDecoder().decode([Todo].self, from: response.knowledge)
print(response.statusCode)
print(todos.depend)


On this case we have been utilizing the dataTask perform, however when you anticipate the response to be an enormous file, you may need to think about using a downloadTask, or when you’re importing a considerable amount of knowledge when sending the request, you need to select the uploadTask perform. 💡


So on this case we needed to manually decode the Todo object from the uncooked HTTP response knowledge, however we are able to use the decodable pipeline to make issues much more easy.


let baseUrl = HttpUrl(host: "jsonplaceholder.typicode.com")
let shopper = UrlSessionHttpClient(session: .shared, log: true)


let pipeline = HttpDecodablePipeline<[Todo]>(url: baseUrl.path("todos"),
                                             technique: .get,
                                             decoder: .json(JSONDecoder(), validators: [
                                                HttpStatusCodeValidator(.ok),
                                                HttpHeaderValidator(.key(.contentType)) {
                                                    $0.contains("application/json")
                                                },
                                             ]))

let todos = attempt await pipeline.execute(shopper.dataTask)
print(todos.depend)


As you’ll be able to see, on this case the as an alternative of returning the response, the pipeline can carry out extra validation and the decoding utilizing the offered decoder and validators. You possibly can create your individual validators, there’s a HttpResponseValidator protocol for this function.


The encodable pipeline works like the identical, you’ll be able to specify the encoder, you’ll be able to present the encodable object and you will get again a HttpResponse occasion.


let shopper = UrlSessionHttpClient(session: .shared, log: true)
        
let todo = Todo(id: 1, title: "lorem ipsum", accomplished: false)

let pipeline = HttpEncodablePipeline(url: baseUrl.path("todos"),
                                     technique: .put up,
                                     physique: todo,
                                     encoder: .json())

let response = attempt await pipeline.execute(shopper.dataTask)

print(response.statusCode == .created)


The codable pipeline is a mixture of the encodable and decodable pipeline. 🙃


let baseUrl = HttpUrl(host: "jsonplaceholder.typicode.com")
let shopper = UrlSessionHttpClient(session: .shared, log: true)

let todo = Todo(id: 1, title: "lorem ipsum", accomplished: false)

let pipeline = HttpCodablePipeline<Todo, Todo>(url: baseUrl.path("todos", String(1)),
                                               technique: .put,
                                               physique: todo,
                                               encoder: .json(),
                                               decoder: .json())

let todo = attempt await pipeline.execute(shopper.dataTask)
print(todo.title)


As you’ll be able to see that is fairly a typical sample, and after we’re speaking with a REST API, we’ll carry out kind of the very same community calls for each single endpoint. SwiftHttp has a pipeline assortment protocol that you should utilize to carry out requests with out the necessity of explicitly establishing these pipelines. Here is an instance:


import SwiftHttp

struct Todo: Codable {
    let id: Int
    let title: String
    let accomplished: Bool
}

struct TodoApi: HttpCodablePipelineCollection {

    let shopper: HttpClient = UrlSessionHttpClient(log: true)
    let apiBaseUrl = HttpUrl(host: "jsonplaceholder.typicode.com")

    
    func checklist() async throws -> [Todo] {
        attempt await decodableRequest(executor: shopper.dataTask,
                                   url: apiBaseUrl.path("todos"),
                                   technique: .get)
    }    
}

let todos = attempt await api.checklist()



When utilizing a HttpCodablePipelineCollection you’ll be able to carry out an encodable, decodable or codable request utilizing an executor object. This can cut back the boilerplate code wanted to carry out a request and every part goes to be kind secure because of the generic protocol oriented networking layer. You possibly can setup as many pipeline collections as you want, it’s potential to make use of a shared shopper or you’ll be able to create a devoted shopper for every.


By the best way, if one thing goes incorrect with the request, or one of many validators fail, you’ll be able to all the time examine for the errors utilizing a do-try-catch block. 😅


do {
    _ = attempt await api.checklist()
}
catch HttpError.invalidStatusCode(let res) {
    
    let decoder = HttpResponseDecoder<CustomError>(decoder: JSONDecoder())
    do {
        let error = attempt decoder.decode(res.knowledge)
        print(res.statusCode, error)
    }
    catch {
        print(error.localizedDescription)
    }
}
catch {
    print(error.localizedDescription)
}



That is how SwiftHttp works in a nutshell, after all you’ll be able to setup customized encoders and decoders, however that is one other subject. In case you are within the mission, be happy to present it a star on GitHub. We’ll use it sooner or later rather a lot each on the shopper and server facet. ⭐️⭐️⭐️





Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments