Search code examples
ssltwiliotwilio-api

Twilio requests.exceptions.SSLError: HTTPSConnectionPool(host='api.ap1.twilio.com', port=443):


I am trying to send a custom sms to a user via twilio but getting ssl error

This is how I am doing. When I try this code

message = twilio_client.messages.create(
    body=f"Your OTP is: {new_otp}",
    from_=settings.TWILIO_PHONE_NUMBER,
    to=to_phone_number
)

where twilio_client is

twilio_client = Client(
    settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN, region="ap1"
)

I get the following error after this running this part of the code

requests.exceptions.SSLError: HTTPSConnectionPool(host='api.ap1.twilio.com', port=443): Max retries exceeded
    with url: /2010-04-01/Accounts/AC871e4afa1d16f5f1a892a7af250eabf2/Messages.json 
    (Caused by SSLError(SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED]
    certificate verify failed: Hostname mismatch,
    certificate is not valid for 'api.ap1.twilio.com'. (_ssl.c:1007)")))

based on online research I checked the url that this part is referring that is

https://api.ap1.twilio.com/2010-04-01/Accounts/AC871e4afa1d16f5f1a892a7af250eabf2/Messages.json

but when I check with Postman it gives me 404 not found response


Solution

  • Found the solution, I just removed region="ap1" from the twilio_client now it works correctly so instead of

    twilio_client = Client(
        settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN, region="ap1"
    )
    

    use

    twilio_client = Client(
        settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN
    )