All Projects → codecat15 → HttpUtility

codecat15 / HttpUtility

Licence: MIT license
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.

Programming Languages

swift
15916 projects
ruby
36898 projects - #4 most used programming language
objective c
16641 projects - #2 most used programming language

Projects that are alternatives of or similar to HttpUtility

Netfox
A lightweight, one line setup, iOS / OSX network debugging library! 🦊
Stars: ✭ 3,188 (+11285.71%)
Mutual labels:  request, response, urlsession, urlrequest
Alamofire
Elegant HTTP Networking in Swift
Stars: ✭ 36,896 (+131671.43%)
Mutual labels:  request, response, urlsession, urlrequest
active endpoint
[ARCHIVE] 🔧 ActiveEndpoint is middleware for Rails application that collect and analize request and response per request for route endpoint. It works with minimum affecting to application response time.
Stars: ✭ 13 (-53.57%)
Mutual labels:  request, response
Aura.http
HTTP Request and Response tools
Stars: ✭ 69 (+146.43%)
Mutual labels:  request, response
Netclient Ios
Versatile HTTP Networking in Swift
Stars: ✭ 117 (+317.86%)
Mutual labels:  request, response
Ngx Restangular
Restangular for Angular 2 and higher versions
Stars: ✭ 787 (+2710.71%)
Mutual labels:  request, response
Guzzlette
🌀 Guzzle integration into Nette Framework (@nette)
Stars: ✭ 19 (-32.14%)
Mutual labels:  request, response
Kitura Net
Kitura networking
Stars: ✭ 98 (+250%)
Mutual labels:  request, response
Examples
Examples of Mock Service Worker usage with various frameworks and libraries.
Stars: ✭ 163 (+482.14%)
Mutual labels:  request, response
reqres
Powerful classes for http requests and responses
Stars: ✭ 36 (+28.57%)
Mutual labels:  request, response
izzyparser-ios
IzzyParser is an iOS library for serializing and deserializing JSON:API objects
Stars: ✭ 19 (-32.14%)
Mutual labels:  request, response
Fast Cgi Client
A PHP fast CGI client for sending requests (a)synchronously to PHP-FPM
Stars: ✭ 478 (+1607.14%)
Mutual labels:  request, response
Swiftyjson
The better way to deal with JSON data in Swift.
Stars: ✭ 21,042 (+75050%)
Mutual labels:  request, response
Alagarr
🦍 Alagarr is a request-response helper library that removes the boilerplate from your Node.js (AWS Lambda) serverless functions and helps make your code portable.
Stars: ✭ 58 (+107.14%)
Mutual labels:  request, response
Wiremock.net
WireMock.Net is a flexible library for stubbing and mocking web HTTP responses using request matching and response templating. Based on the functionality from http://WireMock.org, but extended with more functionality.
Stars: ✭ 408 (+1357.14%)
Mutual labels:  request, response
WaterPipe
URL routing framework, requests/responses handler, and HTTP client for PHP
Stars: ✭ 24 (-14.29%)
Mutual labels:  request, response
psr7-http-message
💫 PSR #7 [HTTP Message Interface] to Nette Framework (@nette)
Stars: ✭ 17 (-39.29%)
Mutual labels:  request, response
Cors
🔮Supported(Laravel/Lumen/PSR-15/Swoft/Slim/ThinkPHP) - PHP CORS (Cross-origin resource sharing) middleware.
Stars: ✭ 266 (+850%)
Mutual labels:  request, response
Holen
Declarative fetch for React
Stars: ✭ 152 (+442.86%)
Mutual labels:  request, response
chronosjs
JS Channels (Events / Commands / Reqest-Response / Courier) Mechanism
Stars: ✭ 35 (+25%)
Mutual labels:  request, response

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].