Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 818
ralphthemagician Avatar asked Dec 11 '25 17:12

ralphthemagician


2 Answers

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
like image 183
Ram G Avatar answered Dec 14 '25 07:12

Ram G


Still seems to break on me an just returns: -bash: !DOCTYPE: event not found

That's an error from the bash shell. You would need to escape the ! as \! yourself. But you'd be better off reading from a file, I think. Instead of -d data use -d @datafile. (Or -d @- to read from stdin).

like image 35
sourcejedi Avatar answered Dec 14 '25 07:12

sourcejedi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!