Alamofire Custom Headers
May 01, 2015

A reader trying to hook up to a Mashape API using Alamofire in Swift just emailed to ask how to handle custom headers (Thanks Claire!). She needs to pass 2 headers with her GET request:

  • X-Mashape-Key: MY_API_KEY
  • Accept: application/json

This curl statement works:

curl --get --include 'https://mashape-community-urban-dictionary.p.mashape.com/define?term=wat' \
-H 'X-Mashape-Key: MY_API_KEY' \
-H 'Accept: application/json'

So how can we make this call work with Alamofire?

This tutorial has been updated to use Swift 2.2, Xcode 7.3, Alamofire 3.3 and SwiftyJSON 2.3.

Looking for Swift 3.0 & Alamofire 4.0? Here’s a new post on handling custom HTTP headers

When dealing with custom headers in Alamofire requests you might need to include a header for all of your API calls or just for a single call. We’ll show how to handle both of those scenarios.

Session Custom Headers

Often, if an API key is needed it then it needs to be provided with all of the calls to an API. The easiest way to handle that is to use a router to create the URL requests and include the header. You can also just set up creating URL requests in your code without a router but a router is a good way to make sure the API key gets included with all of your requests. Here’s what the code in a router that creates a URL request might look like:


let URLRequest = NSMutableURLRequest(URL: url)
      
let encoding = Alamofire.ParameterEncoding.JSON
let (encodedRequest, _) = encoding.encode(URLRequest, parameters: params)

encodedRequest.HTTPMethod = method.rawValue

return encodedRequest

To include the header, just add it to the NSMutableURLRequest:


let URLRequest = NSMutableURLRequest(URL: url)
URLRequest.setValue("MY_API_KEY", forHTTPHeaderField: "X-Mashape-Key")
// ...

Then pass the URL request to Alamofire.request() and the header will get included in the network call:


Alamofire.request(URLRequest).responseJSON { response in
  // ...
}

Per Request Headers

What if we want to set a header for a single request? Again, just set up a URL request and add the header:


let urlString = "https://mashape-community-urban-dictionary.p.mashape.com/define?term=hipster"
if let url = NSURL(string: urlString) {
  let URLRequest = NSMutableURLRequest(URL: url)
  URLRequest.setValue("MY_API_KEY", forHTTPHeaderField: "X-Mashape-Key")
  URLRequest.HTTPMethod = "GET"
  Alamofire.request(URLRequest).responseJSON { response in
    print(response.result.error)
    print(response.result.value)
  }
}

Like before we:

  • Create an NSMutableURLRequest
  • Add the header to it using setValue(forHTTPHeaderField:)
  • Use Alamofire.request(URLRequest) to make the networking call

If you’re using an Alamofire manager the technique is the same, just use manager.request(URLRequest) in the last step.

And That’s All for Alamofire Custom Headers

Now you know how to add HTTP headers to Alamofire API calls. If you’d like more Swift tutorials like this one, sign up below to get them sent directly to your inbox. Feel free to come back and visit too, we’re pretty friendly around here but we’ll understand if it’s just easier for us to come to you :)

P.S. If you’re looking for APIs to play with to develop your skills, check our Mashape. They have tons of free APIs for your coding pleasure.

P.P.S. If you run into any issues with these tutorials or anything else you’re doing in Swift, I’m happy to help. Either leave a comment or email me.

Making your first Swift app that uses a web service can be overwhelming

It seems like every time you try to figure it out you just add more things to learn to your list: REST, Alamofire, parsing JSON, OAuth, App Transport Security, setting headers, …

But it doesn’t have to be confusing. In this free 5-part course, we’ll work through what you really need to know, one step at a time, building our skills as we go. (And get free Swift tutorials, sent straight to your inbox.)

iOS Apps with REST APIs Cover

With iOS Apps with REST APIs ebook I’ll teach you how to build Swift apps that get their data from web services without hundreds of pages about flatmap and Core Whatever. iOS Apps with REST APIs ebook is the book I wish I had on my first iOS contract when I was struggling to figure out how to get the API data showing up in the app I was building.

Other Posts You Might Like