adaptRequest method is called before making a request allowing you to transform it adding headers, changing path, …
rescueRequestError is called whenever the request fail. You’ll have a chance to retry the request. This can be used to re-authenticate the user for instance
SimpleHTTP
Make HTTP API calls easier. Built on top of URLSession.
Installation
Use Swift Package Manager to install the library:
The package come with 2 modules:
SimpleHTTP
which bring the full framework API described in this READMESimpleHTTPFoundation
which only bring a few addition to Foundation API. See this article or API doc to have a glimpse of what is provided.Basic Usage
Building a request
You make requests by creating
Request
objects. You can either create them manually or provide static definition by extendingRequest
:This defines a
Request.login(_:)
method which create a request targeting “login” path by sending aUserBody
and expecting aUserResponse
as response.Sending a request
You can use your request along
URLSession
by converting it into aURLRequest
by callingrequest.toURLRequest(encoder:relativeTo:accepting)
.You can also use a
Session
object.Session
is somewhat similar toURLSession
but providing additional functionalities:A few words about Session:
baseURL
will be prepended to all call pathsURLSession
instance if ever neededSend a body
Request support two body types:
Encodable
To send an Encodable object just set it as your Request body:
Multipart
You can create multipart content from two kind of content
URL
)Data
)First example show how to create a request sending an audio file as request body:
Second example show same request but this time audio file is just some raw unknown data:
Note you can add multiple contents inside a
MultipartFormData
. For instance here we send both a audio file and an image:Constant paths
You can declare constant paths if needed (refer to Path documentation to see more):
Interceptor
When using Session you can add automatic behavior to your requests/responses using
Interceptor
like authentication, logging, request retrying, etc…RequestInterceptor
RequestInterceptor
allows to adapt and/or retry a request:adaptRequest
method is called before making a request allowing you to transform it adding headers, changing path, …rescueRequestError
is called whenever the request fail. You’ll have a chance to retry the request. This can be used to re-authenticate the user for instanceResponseInterceptor
ResponseInterceptor
is dedicated to intercept and server responses:adaptResponse
change the server outputreceivedResponse
notify about the server final response (a valid output or error)