GithubHelp home page GithubHelp logo

codecat15 / httputility Goto Github PK

View Code? Open in Web Editor NEW
36.0 3.0 12.0 132 KB

HttpUtility is an open source MIT license project which is helpful in making HTTP requests and returns a decoded object from server. Right now this utility only parses JSON.

License: MIT License

Objective-C 1.54% Swift 79.14% Ruby 19.32%
urlsession urlrequest request response swift xcode api json encodable decodable

httputility's Introduction

HttpUtility

HttpUtility is a light weight open source MIT license project which is helpful in making HTTP requests to the server. It uses URLSession to make requests to the API and returns the Result enum containing the decoded object in case of success or a error incase of failure. Right now this utility only decodes JSON response returned by the server.

Build Status Twitter

Purpose of usage

Most of the time iOS application just perform simple HTTP operations which include sending request to the server and getting a response and displaying it to the user. If your iOS app does that then you may use this utility which does not do too much of heavy lifting and just pushes your request to the server and returns you a decoded object.

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate HttpUtility into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'HttpUtility', '~> 1.2'

Using HttpUtility

Introduction

HttpUtility can be used for basic http operations like get, post, put and delete. It uses URLSession to perform operations and is just a wrapper around it.

The best thing about this utility is that it takes a simple URL and returns you a decoded object if the request is successful and returns an error if the request fails. Say good bye to writing loops and custom code to parse JSON response.

Given are the some of the examples on how you can make use of this utility

  1. Get request
  2. Post request
  3. Request with query string parameters
  4. Request with MultiPartFormData
  5. Request with authentication token
  6. Customize JSONDecoder in the Utility
  7. HUNetworkError

GET Request example

let utility = HTTPUtility.shared // using the shared instance of the utility to make the API call 
let requestUrl = URL(string: "http://demo0333988.mockable.io/Employees")
let request = HURequest(withUrl: requestUrl!, forHttpMethod: .get)
        
        utility.request(huRequest: request, resultType: Employees.self) { (response) in
            switch response
           {
            case .success(let employee):
            // code to handle the response

            case .failure(let error):
            // your code here to handle error

           }
        }

POST request example

The httpUtility has an extra parameter "requestBody" where you should attach the data that you have to post to the server, in the given example the RegisterUserRequest is a struct inheriting from the Encodable protocol

let utiltiy = HttpUtility.shared // using the shared instance of the utility to make the API call

let requestUrl = URL(string: "https://api-dev-scus-demo.azurewebsites.net/api/User/RegisterUser")
let registerUserRequest = RegisterUserRequest(firstName: "code", lastName: "cat15", email: "[email protected]", password: "1234")

let registerUserBody = try! JSONEncoder().encode(registerUserRequest)
let request = HURequest(withUrl: requestUrl!, forHttpMethod: .post, requestBody: registerUserBody)

  utility.request(huRequest: request, resultType: RegisterResponse.self) { (response) in
   switch response
    {
      case .success(let registerResponse):
       // code to handle the response

       case .failure(let error):
       // your code here to handle error

     }

GET request with Query string parameters

let utiltiy = HttpUtility.shared // using the shared instance of the utility to make the API call
let request = PhoneRequest(color: "Red", manufacturer: nil)

// using the extension to convert the encodable request structure to a query string url
let requestUrl = request.convertToQueryStringUrl(urlString:"https://api-dev-scus-demo.azurewebsites.net/api/Product/GetSmartPhone")

let request = HURequest(withUrl: requestUrl!, forHttpMethod: .get)
utility.request(huRequest: request, resultType: PhoneResponse.self) { (response) in

    switch response
    {
    case .success(let phoneResponse):
   // code to handle the response

    case .failure(let error):
    // your code here to handle error

   }
}

POST request with MultiPartFormData

let utiltiy = HttpUtility.shared // using the shared instance of the utility to make the API call
let requestUrl = URL(string: "https://api-dev-scus-demo.azurewebsites.net/TestMultiPart")

// your request model struct should implement the encodable protocol
let requestModel = RequestModel(name: "Bruce", lastName: "Wayne")

let multiPartRequest = HUMultiPartRequest(url: requestUrl!, method: .post, request: requestModel)

utility.requestWithMultiPartFormData(multiPartRequest: multiPartRequest, responseType: TestMultiPartResponse.self) { (response) in
            switch response
            {
            case .success(let serviceResponse):
                // code to handle the response

            case .failure(let error):
                // code to handle failure
            }
        }

Authentication Token

let utility = HttpUtility.shared
let token = "your_token"
utility.authenticationToken = token

if you are using a basic or a bearer token then make sure you put basic or bearer before your token starts

Example: Basic token

let basicToken = "basic your_token"
let utility = HttpUtility.shared
utility.authenticationToken = basicToken

Example: Bearer token

let bearerToken = "bearer your_token"
let utility = HttpUtility.shared
utility.authenticationToken = bearerToken

Custom JSONDecoder

At times it may happen that you may need to control the behaviour of the default JSONDecoder being used to decode the JSON, for such scenarios the HTTPUtility provides a default init method where you can pass your own custom JSONDecoder and the HTTPUtility will make use of that Decoder and here's how you can do it

let customJsonDecoder = JSONDecoder()
customJsonDecoder.dateEncoding = .millisecondsSince1970
let utility = HttpUtility.shared
utility.customJsonDecoder = customJsonDecoder

Token and Custom JSONDecoder

At times when you pass the token and the default JSONDecoder is just not enough, then you may use the init method of the utility to pass the token and a custom JSONDecoder both to make the API request and parse the JSON response

let utility = HttpUtility.shared
let customJsonDecoder = JSONDecoder()
customJsonDecoder.dateEncoding = .millisecondsSince1970

let bearerToken = "bearer your_token"

utility.customJsonDecoder = customJsonDecoder
utility.authenticationToken = bearerToken

HUNetworkError

The HUNetworkError structure provides in detail description beneficial for debugging purpose, given are the following properties that will be populated in case an error occurs

  1. Status: This will contain the HTTPStatus code for the request that we receive from the server.

  2. ServerResponse: This will be the JSON string of the response you received from the server. (not to be confused with error parameter) on error if server returns the error JSON data that message will be decoded to human readable string.

  3. RequestUrl: The request URL that you just called.

  4. RequestBody: If you get failure on POST request this property would contain a string representation of the HTTPBody that was sent to the server.

  5. Reason: This property would contain the debug description from the error closure parameter.

This utility is for performing basic tasks, and is currently evolving, but if you have any specific feature in mind then please feel free to drop a request and I will try my best to implement it

httputility's People

Contributors

codecat15 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

httputility's Issues

How to return result or response to calling functinon?

I want to return the response from API to where it is called from. like this:

case .success(let driver):
                
            // code to handle the response
//                print("DRIVER: \(String(describing: driver))")
               
                return driver

How can I do such return?

Or any other work around?

I need to have all data in driver when I do:

driver = Driver().getDriver(id)

How to return from success closure?

SSL Pinning

The user should be able to add a configuration with the details of SSL pinning to the utility something like this

let utility = HttpUtility.shared
utility.sslConfiguration = HUSSLConfiguration(some-ssl-details)

Multiple image upload

The utility should be able to upload multiple images parallelly and must return the URL link of those images to the end-user.

The images can be uploaded in multiform, byte array

Before uploading, the developer can select compression if they need to compress the image before sending it to the server.

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.