Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom HTTP Headers with Swift 3 or 4 and Alamofire 4.0-4.7: See https://grokswift.com/custom-headers-alamofire4-swift3/ for explanations
// MARK: - Adding a header to a single request
func doRequestWithHeaders1() {
let headers: HTTPHeaders = [
"X-Mashape-Key": MY_API_KEY,
"Accept": "application/json"
]
Alamofire.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh", headers: headers)
.responseJSON { response in
debugPrint(response)
}
// MARK: - To make sure the headers are sent, use debugPrint on the request
let request = Alamofire.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh", headers: headers)
.responseJSON { response in
debugPrint(response)
}
debugPrint(request)
}
// MARK: - Adding headers to all requests in the session
// store sessionManager so it doesn't get deallocated while we're waiting for the network call to finish
var sessionManager: Alamofire.SessionManager?
func doRequestWithHeaders2() {
// get the default headers
var headers = Alamofire.SessionManager.defaultHTTPHeaders
// add your custom headers
headers["API-Version"] = "2.0"
headers["X-Mashape-Key"] = MY_API_KEY
// create a custom session configuration
let configuration = URLSessionConfiguration.default
// add the headers
configuration.httpAdditionalHeaders = headers
// create a session manager with the configuration
self.sessionManager = Alamofire.SessionManager(configuration: configuration)
// make calls with the session manager
sessionManager?.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh")
.responseJSON { response in
debugPrint(response)
}
}
// MARK: - Add headers when using a URLRequest
func doRequestWithHeaders3() {
if let url = URL(string: "https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh") {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue(MY_API_KEY, forHTTPHeaderField: "X-Mashape-Key")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
Alamofire.request(urlRequest)
.responseJSON { response in
debugPrint(response)
}
}
}
// Alternatively:
func doRequestWithHeaders4() {
if let url = URL(string: "https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh") {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
var headers: HTTPHeaders
if let existingHeaders = urlRequest.allHTTPHeaderFields {
headers = existingHeaders
} else {
headers = HTTPHeaders()
}
headers["X-Mashape-Key"] = MY_API_KEY
headers["Accept"] = "application/json"
urlRequest.allHTTPHeaderFields = headers
let request = Alamofire.request(urlRequest)
.responseJSON { response in
debugPrint(response)
}
debugPrint(request)
}
}
// MARK: - Use an Alamofire RequestAdapter to add headers to all calls in the session
class MashapeHeadersAdapter: RequestAdapter {
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
var urlRequest = urlRequest
urlRequest.setValue(MY_API_KEY, forHTTPHeaderField: "X-Mashape-Key")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
return urlRequest
}
}
func doRequestWithHeaders5() {
// Then to make the call:
// get a session manager and add the request adapter
let sessionManager = Alamofire.SessionManager.default
sessionManager.adapter = MashapeHeadersAdapter()
// make calls with the session manager
let request = sessionManager.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh")
.responseJSON { response in
debugPrint(response)
}
debugPrint(request)
}
@artem-sherbachuk

This comment has been minimized.

Copy link

artem-sherbachuk commented Nov 1, 2016

nice

@nthrussell

This comment has been minimized.

Copy link

nthrussell commented Dec 1, 2016

your book will change my life ... I can feel that and I will always be thankful to you for this. Thanks Christina ..

@Hamasn

This comment has been minimized.

Copy link

Hamasn commented Feb 10, 2017

really good demo.

@shashank19909

This comment has been minimized.

Copy link

shashank19909 commented May 12, 2017

Hi small doubt
I have added a adapter to my session manager, so all my API calls will have headers I have set in adapt function.
Now I have a scenario where I have to add one extra field to header for a specific API call.

So if I add header in the request like this
Alamofire.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh", headers: headers)

Will the headers I set in adapter be replaced entirely or will the new header params be added along with the previous header params?

@namanhams

This comment has been minimized.

Copy link

namanhams commented Nov 17, 2017

Very nice ! Thanks !

@cmoulton

This comment has been minimized.

Copy link
Owner Author

cmoulton commented Jan 15, 2018

@shashank19909 Sorry, just saw your question now. If you're adding an extra header field then it'll just add your field, it won't remove the existing ones.

@VSG24

This comment has been minimized.

Copy link

VSG24 commented Mar 28, 2018

Good one

@bartleby

This comment has been minimized.

Copy link

bartleby commented May 7, 2018

nice

@CoalWood

This comment has been minimized.

Copy link

CoalWood commented Jun 23, 2018

I found your examples to be a BIG Help. Here is one I am using that has "headers" for Yelp Authorization. Apparently Yelp very recently changed how they handle Authorization so not may examples exist as of this post time. So, here it is:

func doMashape() -> Void {

let fileURL = "https://api.yelp.com/v3/businesses/search?term=Restaurants"
let parameters : Parameters = ["radius": "10000", "latitude": "29.94", "longitude": "-85.41"]
let headers: [String : String] = ["Authorization": "Bearer <YOUR YELP APP_ID GOES HERE>"]
Alamofire.request(fileURL, method: .get, parameters: parameters, headers: headers).responseJSON {
  response in
    if let receivedString = response.result.value {
      print()
      print("Here \(receivedString)")
    }
}

Note: This entry does not include the <> and has a simple space between Bearer and APP_ID.

@lakshaychhabra

This comment has been minimized.

Copy link

lakshaychhabra commented Jun 26, 2018

How to Handle errors in URL in it?
Suppose by chance user entered character like "/" then it crashes the program

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.