Mailchimp RESTful API 3.0 HTTP Basic Auth

6.2k views Asked by At

I'm trying to use the Mailchimp API version 3.0 with basic auth. I'm using Classic ASP.

The Json response is always: "API Key Missing".

Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
HttpReq.open "GET", "https://us4.api.mailchimp.com/3.0/", False
HttpReq.setRequestHeader "Content-Type", "application/json"
HttpReq.setRequestHeader "apikey", "xxxxxx"
HttpReq.send ""
Response.Write  HttpReq.ResponseText
Set HttpReq = Nothing

I'm sending it as a header.

What am I doing wrong..?

3

There are 3 answers

2
Stephen Last On BEST ANSWER

The answer is:

HttpReq.setRequestHeader "Authorization", "apikey xxxxxx"
0
TooMuchPete On

If you're trying to use Basic Auth, you need to actually follow the spec. You can build the header yourself using the wiki article as your guide, but the easiest thing is to just use your HTTP Library's built-in support for that. In your case, this will probably help.

To roll your own, you need two pieces of information. The first is the username the second is the password. For MailChimp v3.0, the username can be anything. I tend to use 'apikey' as the username. The password is the API Key itself. Let's say my API Key is 'xxxxxxxxxx-yyy'. Now, you Base 64 Encode the string apikey:xxxxxxxxxx-yyy. That gives me YXBpa2V5Onh4eHh4eHh4eHgteXl5. Now the header I create is:

Authorization: Basic YXBpa2V5Onh4eHh4eHh4eHgteXl5

The method you're using will work, but is very custom to MailChimp and might confuse future visitors to your code.

0
Mike.R On

I see that the question was based on #C but I had the same problem with java.(I am new to java so fell free to edit my code).

public String get(String url) throws IOException {
     HttpGet get = new HttpGet(url);
     String apiEncode = "apikey:9590e52MyAPI8-us9";
     String encoding = Base64.encodeBytes(apiEncode.getBytes());                     
     get.setHeader("Authorization","Basic " + encoding );
     HttpResponse response = http.execute(get);

    if (response.getEntity() != null) {
        return EntityUtils.toString(response.getEntity(), "UTF-8").trim();
    } else {
        throw new IOException(response.getStatusLine().toString());
    }
}