How to Set a Canonical URL in Python

Cloudmersive
2 min readJul 22, 2021

Do you have a canonical URL set for your web pages? If not, your site could be at risk for duplicate content and inaccurate displays of information. By setting the canonical URL for an HTML document, you are sending a message to search engines and other indexers about which pages are duplicates of each other, which is an important element of search engine optimization. In this quick tutorial, we will demonstrate how you can use an API in Python to automatically set a rel=canonical URL for an HTML document.

Let’s begin by running this command to install the package:

pip install cloudmersive-convert-api-client

Once the installation is complete, we are ready to input the file or file URL, the canonical URL to set, and our API key into the below example code:

from __future__ import print_function
import time
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_convert_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# create an instance of the API class
api_instance = cloudmersive_convert_api_client.EditHtmlApi(cloudmersive_convert_api_client.ApiClient(configuration))
canonical_url = 'canonical_url_example' # str | The HTML canonical URL to set.
input_file = '/path/to/inputfile' # file | Optional: Input file to perform the operation on. (optional)
input_file_url = 'input_file_url_example' # str | Optional: URL of a file to operate on as input. (optional)
try:
# Sets the rel canonical URL for the HTML document
api_response = api_instance.edit_html_html_set_rel_canonical(canonical_url, input_file=input_file, input_file_url=input_file_url)
pprint(api_response)
except ApiException as e:
print("Exception when calling EditHtmlApi->edit_html_html_set_rel_canonical: %s\n" % e)

And with that your rel=canonical URL will be set! If you need to obtain an API key, you can do so by registering for a free account on the Cloudmersive website; this provides 800 monthly calls across our library of APIs.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.