Get Data through an API using PFX Certificates - Python Script
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Mute
- Printer Friendly Page
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Notify Moderator
Hello - I had a request to use an API to retrieve Data from an END POINT but this API was set up to use PFX certificate. Some of the challenges I found is that I could not make the Download Tool to read the PFX certificate so it was not possible to use the Download Tool to complete this task. Another challenge was the fact that while writing the Script some Python functionalities were deprecated (Like the PyOpenSSL load_pkcs12 is deprecated), So the option was to use a New Python Script using cryptography to make it work. The below Script is a sample of what I used to make the API work:
pfx_path = "YOUR PFX CERT PATH"
pw = "PASSWORD-GOES-HERE".encode('utf-8')
url = 'YOUR_END_POINT_INFO'
with open(pfx_path , "rb") as f:
pfx_data = f.read()
private_key, certificate, additional_certificates = pkcs12.load_key_and_certificates(pfx_data, pw, default_backend())
with tempfile.NamedTemporaryFile(suffix=".pem", delete=False) as temp_key_file:
temp_key_file.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
))
temp_key_file.flush()
with tempfile.NamedTemporaryFile(suffix=".pem", delete=False) as temp_cert_file:
temp_cert_file.write(certificate.public_bytes(serialization.Encoding.PEM))
temp_cert_file.flush()
response = requests.get(url, cert=(temp_cert_file.name, temp_key_file.name))
# Check the response
if response.status_code == 200:
print("Data retrieved successfully")
else:
print(f"Failed to retrieve data: {response.status_code}")
data = response.json()
df = pd.DataFrame(data)
f.close()
os.unlink(temp_key_file.name)
os.unlink(temp_cert_file.name)
Alteryx.write(df,1)