How to escape characters in part of a JSON POST request with CURL?

ralphthemagician picture ralphthemagician · Aug 28, 2012 · Viewed 17.8k times · Source

So, I'm trying to use a service called Postmark to send a formatted HTML email. They have some API documentation here, and they give this example on how to use CURL:

$: curl -X POST "http://api.postmarkapp.com/email" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "X-Postmark-Server-Token: ed742D75-5a45-49b6-a0a1-5b9ec3dc9e5d" \
-v \
-d "{From: '[email protected]', To: '[email protected]', Subject: 'Postmark test', HtmlBody: '<html><body><strong>Hello</strong> dear Postmark user.</body></html>'}"

So, that's all good and works just fine when I use my own token. The problem is when I add my own HtmlBody. If I send a simple message, it works just fine. As soon as I add certain special characters, it breaks. For example, if I do something like this:

-d "{From: '[email protected]', To: '[email protected]', Subject: 'Postmark test', HtmlBody: '<!DOCTYPE html><html><body><strong>Hello</strong> dear Postmark user.</body></html>'}"

It breaks because of the !. How can I fix this?


UPDATE: As sourcejedi pointed out I am running this from the shell (bash), so the ! issue makes sense to me now. I moved the JSON string to a separate file called email.json and loaded that using -d @email.json. That worked for a simple email with <!DOCTYPE>, but I'm still getting the following error when I try to load the full HTML:

{"ErrorCode":402,"Message":"Received invalid JSON input."}

I believe this has to do with some other special characters. I get the same error when I use --data-urlencode @email.json.

Answer

Ram G picture Ram G · Aug 28, 2012

You need to use --data-urlencode, so it should be like curl -X POST --data-urlencode

When I tested on my end..

* About to connect() to api.postmarkapp.com port 80 (#0)
*   Trying 50.56.54.211... connected
> POST /email HTTP/1.1
> User-Agent: curl/7.23.1 (x86_64-pc-win32) libcurl/7.23.1 OpenSSL/0.9.8r zlib/1
.2.5
> Host: api.postmarkapp.com
> Accept: application/json
> Content-Type: application/json
> X-Postmark-Server-Token: ed742D75-5a45-49b6-a0a1-5b9ec3dc9e5d
> Content-Length: 164