Create a Post with Image in Lead Media

This tutorial explains how to create an article with an image in the lead media position.

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 a URL and obtain its ID and other useful information.

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 has been uploaded, create a new draft using the Drafts API with the uploaded image in the lead media spot.

response = requests.post(
     'https://{}/api/1.3/drafts'.format(API_DOMAIN),
    params={'api_key': API_KEY},
    json={
        'headline': 'Article with image in lead media',
        'body': '<p>This is a HTML piece.</p>',
        'image_id': image_api_response['id'],
        'media': image_api_response['shortcode'],
        'manual_image_crops': image_api_response['manual_image_crops'],
        'image_size': '{}x{}'.format(image_api_response['width'], image_api_response['height'])
    }
)
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'])