I am using Alamofire to send a request to MailChimp to add a user to a list
MailChimp's docs say:
There are 2 authentication methods for the API: HTTP Basic authentication and OAuth2. The easiest way to authenticate is using HTTP Basic authentication. Enter any string as your username and supply your API Key as the password.
The request I wrote for Alamofire:
let params: [String : AnyObject] = ["email_address": email, "status": "subscribed", "merge_fields": [ "FNAME": name]]
guard let url = "https://us10.api.mailchimp.com/3.0/lists/<listID>/members/".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) else { return }
Alamofire.request(.POST, url, parameters: params, encoding: .URL)
.authenticate(user: "apiKey", password: "<apikey>")
.responseJSON { response in
if response.result.isFailure {
}
else if let responseJSON = response.result.value as? [String: AnyObject] {
}
}
I checked that the API key is correct by using it to access their playground: https://us1.api.mailchimp.com/playground/
The response I get back states that the API key was not included:
Your request did not include an API key.
Where have I gone wrong?
Swift 3
Make sure you take a look at MailChimp's Error Glossary. A 401 indicates that your API key is not being read properly.
For Swift 3, the header construction in Abbey Jackson's answer needs to be updated to this. Otherwise it totally works.
let credentialData = "AnyString:\(apiKey)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString()
let headers = ["Authorization": "Basic \(base64Credentials)"]
Here's an example that uses Request.authorizationHeader
instead.
let apiKey: String = "xxxxxxxxxxxxxxx2b-us11" // note the 'us11'
let baseUrl: String = "https://us11.api.mailchimp.com/3.0" // note the 'us11'
let listId: String = "xxxxxx2f"
func createListMember() {
let url = "\(baseUrl)/lists/\(listId)/members"
guard let authorizationHeader = Request.authorizationHeader(user: "AnyString", password: apiKey) else {
print("!authorizationHeader")
return
}
let headers: HTTPHeaders = [
authorizationHeader.key: authorizationHeader.value
]
let parameters: Parameters = [
"email_address": email,
"status": "subscribed"
]
// perform request (make sure you're using JSONEncoding.default)
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
//.authenticate(user: "AnyString", password: apiKey) // this doesn't work
.validate()
.responseJSON {(response) in
print(response)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With