How to use WordPress REST API from python?

WordPress REST API is very useful. used heavily by the WordPress developer community. The WordPress REST API integration to the WordPress core made WordPress more powerful.

In this post, we are going to discuss step by step guide about doing WordPress REST API calls from the python script.

Step 1: Define WordPress end point

wordpress_token = ""
wordpress_credential = {"username": "<wp-username>", "password": "<wp-password>"}
WP_API_ENDPOINT = "http://domain.cefalo.com/wp-json"

Step 2: Generate WordPress token

def generate_wordpress_token():
    global wordpress_token
    token_url = WP_API_ENDPOINT + "/jwt-auth/v1/token"

    try:
        token_response = requests.post(url = token_url, data = wordpress_credential)
        if token_response and token_response.status_code == 200:
            token_data = token_response.json()
            if token_data:
                wordpress_token = token_data["token"]
    except (OSError, IOError) as e:
        logger.critical("Could not generate the token using this endpoint: %s.", token_url)

Step 3: Use post call to create post in WP

def import_post_to_wordpress(pp_json):
    global wordpress_token
    result = {}

    if pp_json['title']:
        if not wordpress_token:
            generate_wordpress_token()

        if wordpress_token:
            create_post_url = WP_API_ENDPOINT + "/wp/v2/product"
            headers = {'content-type': 'application/json', 'Authorization': "Bearer " + wordpress_token}

            pp_json['slug'] = slugify(pp_json['title'])
            get_response = requests.get(create_post_url + "?slug=" + pp_json['slug']).json()

            if get_response:
                post_json = get_response[0]
                if post_json:
                    update_post_url = create_post_url + "/" + str(post_json['id']);
                    try:
                        put_response = requests.put(url = update_post_url, json=pp_json, headers=headers)
                        if put_response and put_response.status_code == 200:
                            result = put_response.json()
                    except (OSError, IOError) as e:
                        logger.critical('Could not update the book: %s.', post_json['id'])
            else:
                try:
                    post_response = requests.post(url = create_post_url, json=pp_json, headers=headers)
                    if post_response and post_response.status_code == 201:
                        result = post_response.json()
                except (OSError, IOError) as e:
                    logger.critical('Could not create the book %s.', pp_json['title'])

    if result:
        logger.info('Imported post in WP %s.', result["id"])
        return result["id"]