Thursday, February 2, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

Async HTTP API clients in Swift

learningcode_x1mckf by learningcode_x1mckf
September 8, 2022
in Swift
0
Async HTTP API clients in Swift
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


Introducing SwiftHttp

You might also like

The abstract Vapor service factory design pattern

SwiftNIO tutorial – The echo server

Introducing – Vapor cheatsheet – The.Swift.Dev.

An superior Swift HTTP library to quickly create communication layers with API endpoints. The library tries to separate the consumer request logic from the request constructing and response dealing with. That is the principle motive 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 primarily based on Foundation networking.


So the consumer is liable 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, methodology: .get, headers: [:], physique: nil)


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


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


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


let activity = Activity 
    let api = TodoApi()
    _ = attempt await api.listing()


DispatchQueue.international().asyncAfter(deadline: .now() + .milliseconds(10)) 
    activity.cancel()


do 
    let _ = attempt await activity.worth

catch 
    if (error as? URLError)?.code == .cancelled 
        print("cancelled")
    


It is a neat tick, you can even verify the explanation 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 consumer to carry out or cancel a community activity, however often you do not need to work with uncooked knowledge, however encodable and decodable objects. While you work with such objects, you would possibly 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-Type / Accept header fields. šŸ¤”


So we would need to ship extra headers alongside the request, plus it might be good to validate the standing code and response headers earlier than we attempt to parse the information. This looks as if a circulation of frequent operations, first we encode the information, 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 information object. It is a typical use case and SwiftHttp calls this workflow as a pipeline.


There are 4 forms 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 are able to use a HttpRawPipeline and execute our request utilizing a consumer as an executor.


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

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

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


On this case we had been utilizing the dataTask perform, however in the event you anticipate the response to be an enormous file, you would possibly need to think about using a downloadTask, or in the event you’re importing a considerable amount of knowledge when sending the request, it is best 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 consumer = UrlSessionHttpClient(session: .shared, log: true)


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

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


As you’ll be able to see, on this case the as a substitute 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 goal.


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 consumer = UrlSessionHttpClient(session: .shared, log: true)
        
let todo = Todo(id: 1, title: "lorem ipsum", accomplished: false)

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

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

print(response.statusCode == .created)


The codable pipeline is a mix of the encodable and decodable pipeline. šŸ™ƒ


let baseUrl = HttpUrl(host: "jsonplaceholder.typicode.com")
let consumer = 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)),
                                               methodology: .put,
                                               physique: todo,
                                               encoder: .json(),
                                               decoder: .json())

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


As you’ll be able to see that is fairly a typical sample, and once we’re speaking with a REST API, we will 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 consumer: HttpClient = UrlSessionHttpClient(log: true)
    let apiBaseUrl = HttpUrl(host: "jsonplaceholder.typicode.com")

    
    func listing() async throws -> [Todo] 
        attempt await decodableRequest(executor: consumer.dataTask,
                                   url: apiBaseUrl.path("todos"),
                                   methodology: .get)
        


let todos = attempt await api.listing()



When utilizing a HttpCodablePipelineCollection you’ll be able to carry out an encodable, decodable or codable request utilizing an executor object. This may scale back the boilerplate code wanted to carry out a request and the whole lot 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 doable to make use of a shared consumer or you’ll be able to create a devoted consumer for every.


By the best way, if one thing goes mistaken with the request, or one of many validators fail, you’ll be able to at all times verify for the errors utilizing a do-try-catch block. šŸ˜…


do 
    _ = attempt await api.listing()

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 challenge, be at liberty to present it a star on GitHub. We will use it sooner or later rather a lot each on the consumer and server facet. ā­ļøā­ļøā­ļø





Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

The abstract Vapor service factory design pattern

by learningcode_x1mckf
February 1, 2023
0
The abstract Vapor service factory design pattern

I've written a number of articles about manufacturing unit design patterns on my weblog and this time I might like to speak a couple of particular one, which...

Read more

SwiftNIO tutorial – The echo server

by learningcode_x1mckf
January 27, 2023
0
SwiftNIO tutorial – The echo server

Intoducing SwiftNIO In the event you used a excessive degree net framework, corresponding to Vapor, up to now, you would possibly had some interplay with occasion loops...

Read more

Introducing – Vapor cheatsheet – The.Swift.Dev.

by learningcode_x1mckf
January 23, 2023
0
Introducing – Vapor cheatsheet – The.Swift.Dev.

Out there on Gumroad Thanks for supporting my work by buying the cheatsheet. šŸ™ Download now A whole Vapor framework reference for novices. greater than...

Read more

iCloud Programming Tutorial for iOS: An Introduction

by learningcode_x1mckf
January 18, 2023
0
iCloud Programming Tutorial for iOS: An Introduction

Editor’s observe: This week, we work with Ziad Tamim once more to provide you an introduction of iCloud programming. You’ll learn to save and retrieve knowledge from iCloud.On...

Read more

Easy multipart file upload for Swift

by learningcode_x1mckf
January 18, 2023
0
Easy multipart file upload for Swift

I imagine that you've got already heard in regards to the well-known multipart-data add method that everybody likes to add recordsdata and submit type knowledge, but when not,...

Read more
Next Post
Top 10 Javascript Interview Code-Based Questions(Let’s do brainstorming) | by Ritik Chopra | Nerd For Tech | Aug, 2022

Top 10 Javascript Interview Code-Based Questions(Let’s do brainstorming) | by Ritik Chopra | Nerd For Tech | Aug, 2022

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

8 Java frameworks for embedded development

8 Java frameworks for embedded development

September 6, 2022
How to UseĀ localStorage in JavaScript

How to UseĀ localStorage in JavaScript

September 18, 2022
Elevate K-12 Launches Java and Python Courses to Meet Nationwide Demand

Java Original Coffee Company to Support The Onco’Zine Brief Radio Broadcast and Podcast

January 30, 2023

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • Java :Full Stack Developer – Western Cape saon_careerjunctionza_state
  • Pay What You Want for this Learn to Code JavaScript Certification Bundle
  • UPB Java Jam brings coffeehouse vibes to Taylor Down Under | Culture

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

Ā© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

Ā© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?