Unable to Update Post Content Using Admin API - 2024

Hello everyone,

I’ve been trying to update the content of my post, but unfortunately, I’ve hit a wall.

Here is the Python function I’m using to update the post:

def updateGhostPost(post_id, html):
    # Generate an authentication token
    token = generate_token(api_key)
    
    # Set the headers for the PUT request
    headers = {
        'Authorization': 'Ghost {}'.format(token),
        'Content-Type': 'application/json'
    }
    
    # Construct the URL for updating the post
    update_url = api_url + f'/api/admin/posts/{post_id}/'
    
    # Construct the URL to get the current post data
    get_url = api_url + f'/api/content/posts/{post_id}/?key={api_content_key}'
    
    # Set the headers for the GET request
    headersGet = {
        'Content-Type': 'application/json'
    }
    
    # Send a GET request to retrieve the current post data
    response = requests.get(get_url, headers=headersGet)
    
    # Parse the response JSON to get the post's current updated_at timestamp
    dataResponse = response.json()['posts'][0]
    updated_at = dataResponse['updated_at']

    # Prepare the data for the PUT request with the new HTML content and timestamp
    data = {
        'posts': [{
            'html': html,
            'updated_at': updated_at,
        }],
    }

    # Log the update attempt with the post ID
    print(f"Actualizando post con ID {post_id}")
    
    # Send a PUT request to update the post content
    response = requests.put(update_url, json=data, headers=headers)
    
    # Print the status code of the PUT request
    print("Status Code:", response.status_code)
    
    # Return True if the update is successful
    return True

The requests.put call returns a status code of 200 , indicating success, but the HTML content does not update.

Has anyone experienced a similar issue or have any suggestions on how to resolve this? I would greatly appreciate any help or guidance you can provide.

Thank you in advance!

Best regards

You’re missing source:html, which is required any time you are passing the post body as html instead of lexical.

1 Like

Hi Cathy,

Thank you so much for your response! Your suggestion worked perfectly for me. Here’s the code snippet I used:

    # Construct the URL for updating the post
    update_url = api_url + f'/api/admin/posts/{post_id}/?source=html'
1 Like