How To Consume CloudFlare API Using Python

This tutorial help to access cloudflare Rest API Using Python 3.The cloudflare providing rest api to handle many operation which can you done via cloudflare dashboard.The Cloudflare’s API exposes the entire Cloudflare infrastructure via a standardized programmatic interface.

The CloudFlare API is use HTTPS based requests with json payloads and send JSON responses.You can obtain your API key from the “My Account” page.

What’s CloudFlare

Cloudflare help to webmaster to makes sites lightning fast and also protects them from attacks.They provides content delivery network services, DDoS mitigation, Internet security and distributed domain name server services.

Cloudflare API Types

Cloudflare offers public APIs with three audiences in mind.

  • Cloudflare customers
  • Cloudflare partners
  • Developers

How To Access CloudFlare API

The cloudflare provides v4 rest api to access features.You can use GET, POST, PUT, PATCH, and DELETE method access any resource.All the endpoint is accessed only via the SSL-enabled HTTPS (port 443) protocol.The Cloudflare API sets a maximum of 1,200 requests in a five minute period.

We will install Python dependency

We will use requests package to handle HTTP request.You can install request and flask package using following command –

pip install requests
pip install flask

How To Access CloudFlare zones Using API

We will access zones of CloudFlare using Rest API. The CloudFlare provides GET /zones call to get all available zones.The Http request help to create GET call and access CloudFlare resources.You can also create POST, PUT and DELETE Http request.

from flask import Flask
from flask_restful import Resource, Api
from flask_cors import CORS
import requests

app = Flask(__name__)
CORS(app) ## To allow direct AJAX calls

@app.route('/getZones', methods=['GET'])
def home():
   try:        
    headers = {'X-Auth-Email': 'testemail', 'X-Auth-Key': 'API Key'}
    res = requests.get('https://api.cloudflare.com/client/v4/zones', headers=headers)

    return r.json()

   except Exception as e:
    print('unable to get zones.')
    print(e.strerror)

if __name__ == '__main__':
   app.run(debug = True)

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.