mjmlio / mjml

MJML: the only framework that makes responsive-email easy
https://mjml.io
MIT License
17.08k stars 960 forks source link

How do I post JSON to the API? #903

Closed CodingPeak closed 6 years ago

CodingPeak commented 6 years ago

I can't figure out how I should format my post data when posting to the API. I have a JSON format, but every time I'm getting errors from the API.

The documentation says: image

So the JSON string should be added where it says "string". But how exactly?

I tried: {"mjml":"{"tagName":(...) But of course that wouldn't make sense with those double quotes... Error: The request body is not JSON compliant

So I tried {"mjml":"{\"tagName\":(...) But also no luck... Error: EmptyMJMLError: .render: No MJML to render in options [object Object]

Then I tried leaving the {"mjml" out of it... {"tagName":(...) Error: EmptyMJMLError: No root "<mjml>" or "<mj-body>" found in the file, or "<mj-body>" doesn't contain a child element.

CodingPeak commented 6 years ago

I started over from a different MJML template and encoded the proper JSON to JSON again. (double json encoded, so it escapes all the double quotes etc.)

So I ended up having this {"mjml":"{ \"tagName\": \"mjml\", \"attributes\": { }, \"children\": [ { \"tagName\": \"mj-body\",(...)

Another question: is it possible to pass global styles with JSON to the API?

ngarnier commented 6 years ago

Hey @CodingPeak, indeed you need to encode it so it's valid JSON.

{ "mjml":"{\"tagName\":\"mjml\",\"children\":[{\"tagName\":\"mj-body\",\"children\":[{\"tagName\":\"mj-container\",\"children\":[{\"tagName\":\"mj-section\",\"children\":[{\"tagName\":\"mj-column\",\"children\":[{\"tagName\":\"mj-text\",\"content\":\"Hello World\",\"attributes\":{}}],\"attributes\":{}}],\"attributes\":{}}],\"attributes\":{}}],\"attributes\":{}}],\"attributes\":{}}" }

I guess it worked that time?

About global styles, do you mean using mj-style or mj-attributes? If so, yes you can, the structure follows exactly the same logic.

If you already have MJML templates that you need to convert to JSON, have a look at that lib that can do the job for you (and you can use the -s option to make the output API ready): https://github.com/mjmlio/mjml2json

I'll close because I think the question is answered but let us know if you have other questions either here on Github or on Slack.

CodingPeak commented 6 years ago

Thank you for your answer @ngarnier. Is it possible to include mj-attributes in JSON to use with the API? I read somewhere that it might not be possible to use head and body in JSON.

ngarnier commented 6 years ago

Yep, as mentioned, it's possible :-) (it was not at some point so that may be why you read the opposite somewhere).