Embed Images in Body using Shortcodes

This tutorial explains how to create an article with an embedded image in the post body content.

Requirements

For this tutorial you will need both the Python and requests libraries installed.

Procedure

1. Initialize variables

Set the global variables.

import requests
API_DOMAIN = '<your-secure-domain>'
API_KEY = '<your-api-key>'

2. Upload an image

This code snippet uses the Images API to upload an image using an URL to obtain its shortcode.

image_url = 'http://lorempixel.com/800/400/'
response = requests.post(
    'https://{}/api/1.3/images'.format(API_DOMAIN),
    params={'api_key': API_KEY},
    json={'image_url': image_url}
)
response.raise_for_status()
image_api_response = response.json()
print(image_api_response['id'])

3. Create a draft

Now that the image was uploaded, we need to create a new draft using the Drafts API with the image embedded in the content body.

body_content = '''
     <p>This is a HTML piece than can contain shortcodes</p>
     {}
     <p>This text goes after the embedded image</p>
'''.format(image_api_response['shortcode'])
response = requests.post(
     'https://{}/api/1.3/drafts'.format(API_DOMAIN),
    params={'api_key': API_KEY},
    json={
        'headline': 'Embedded image in article content',
        'body': body_content,
    }
)
response.raise_for_status()
draft_api_response = response.json()
print(draft_api_response['id'])

4. Publish the draft

Finally, publish the draft and print its URL.

response = requests.put(
    'https://{}/api/1.3/drafts/{}'.format(API_DOMAIN, draft_api_response['id']),
    params={'api_key': API_KEY},
    json={'action': 'publish'}
)
response.raise_for_status()
draft_api_response = response.json()
print(draft_api_response['post_url'])