How to Use the Python Requests Module With REST APIs

When you want to interact with data via a REST API, this is called a request. A request is made up of the following components:

Endpoint – How a web page URL is tied to a specific page, an endpoint URL is tied to a specific resource within an API.

Method – Specifies how you’re interacting with the resource located at the provided endpoint. REST APIs can provide methods to enable full Create, Read, Update, and Delete (CRUD) functionality. Here are common methods most REST APIs provide:

GET -> Retrieve existing data
POST -> Add new data
PUT -> Update existing data
PATCH -> Partially update existing data
DELETE -> Delete data

Once a REST API receives and processes an HTTP request, it returns a response with an HTTP status code.
1xx --> Informational response
2xx --> Successful operation
3xx --> Redirection
4xx --> Client error
5xx --> Server error

Headers: You can also retrieve metadata from the response via headers

Case 1: How to create a token using Request Module:

import requests
tokenurl = "http://127.0.0.1:8001/api/v3/cmp/apiToken/"
data = {"username": "abc", "password": "abc@123"}
response = requests.post(tokenurl, data=data)
token = response.json()["token"]

print(token)

How to Retrieve Data With GET:

import requests
tokenurl = "http://localhost:8001/api/v2/api-token-auth/"
data  = { "username": "abc", "password": "abc@1"}
response = requests.post(tokenurl, data=data, verify=False)
token = response.json()["token"]
Orderurl = "http://localhost:8001/api/v2/orders/5/"headers = {"Authorization": f"Bearer {token}"}
response = requests.get(Orderurl, headers=headers).json()
print(response)

How to make a POST request:

import requests
tokenurl = "http://localhost:8001/api/v2/api-token-auth/"
data  = { "username": "abc", "password": "abc@1"}
response = requests.post(tokenurl, data=data, verify=False)
token = response.json()["token"]
Orderurl = "http://localhost:8001/api/v2/orders/"headers = {"Authorization": f"Bearer {token}"}
data={
    "group": "/api/v2/groups/GRP-q2msskgt/",
    "items": {
        "deploy-items": [
            {
                "blueprint": "/api/v2/blueprints/BP-vawml3bg/",
                "blueprint-items-arguments": {
                    "build-item-Add_user_to_group": {
                        "parameters": {
                            "Justification": "hello, Hi",
                            "cloud-name": "Azure"                        }
                    },
                    "build-item-servicenow autoapprove@sd": {
                        "parameters": {
                            "Justification": "hello, Hi",
                            "cloud-name": "Azure"                        }
                    }
                },
                "resource-name": "Automated Cloudbolt Access",
                "resource-parameters": {
                    "Justification": "hello, Hi",
                    "cloud-name": "Azure"                }
            }
        ]
    },
    "submit-now": "true"}
response = requests.post(Orderurl,json=data, headers=headers)
print(response.json())

Use Case:

I am trying to add a custom icon to our branded portal. trying to use a .png as the icon file.

import requests
tokenurl = "http://127.0.0.1:8001/api/v3/cmp/apiToken/"
data = {"username": "abc", "password": "abc@1"}
response = requests.post(tokenurl, data=data)
token = response.json()["token"]
brandeportalurl = "http://127.0.0.1:8001/api/v3/cmp/brandedPortals/"headers = {"Authorization": f"Bearer {token}"}
branded_data = {
    "is_default": False,
    "name": "abc",
    "domain": "abc.cloudbolt.io"}
resp = requests.post(brandeportalurl, files={'custom_banner': open('/home/dell/Pictures/cloudbolt_logo.png', 'rb')}, data=branded_data, headers=headers)
print(resp.json())

Developers should feel free to interact with the API using any clients, libraries or tools that support making http requests. An example of retrieving the top level collections available using cURL, would look something like this, for instance: https://docs.cloudbolt.io/articles/#!cloudbolt-latest-docs/getting-started-api

  1. Using Curl Command:

dell@dell-Latitude-3400:~$ curl -X POST -H "Content-Type: application/json" -d '{"username": "abc", "password": "abc@1"}' --insecure https://10.112.2.63/api/v2/api-token-auth/ -o token.txt

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   278  100   229  100    49    117     25  0:00:01  0:00:01 --:--:--   142


dell@dell-Latitude-3400:~$ cat token.txt

{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImFrdW1hciIsImV4cCI6MTY0OTMxMjY3MywiZW1haWwiOiJha3VtYXJAY2xvdWRib2x0LmlvIiwib3JpZ19pYXQiOjE2NDkzMTIzNzN9.aTT7n6H1fJ-L1K2qEBIKCVCnq0LwDksQiR-5UEyfCIk"}

2. API Client Sample:
Using the sample Python scripts:

zip file: Click here to download

  1. Unpack the zip on a server with Python 2.6, 2.7, or 3.x

  2. cd api_samples/python_client/samples/

  3. Run ./order_blueprint.py -h

  4. Determine which IDs to use and parameters to pass. One easy way to do this is to submit an order from the CloudBolt web UI, then navigate to that order in the API browser (ex. /api/v2/orders/<your_order_id/>), and inspect the items in the order.


 API calls from an interactive Python shell:

  1. cd api_samples/python_client

  2. type: python to start the Python interpreter, and enter the following code:

dell@dell-Latitude-3400:~/Downloads/CloudBolt_API_Samples9-4-4/api_samples/python_client$ python

Python 3.9.4 (default, Sep  7 2021, 12:22:43)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from api_client import CloudBoltAPIClient
>>> username = "abc"
>>> password = "abc@1"
>>> hostname = "10.112.2.63"
>>> c = CloudBoltAPIClient(username, password, host=hostname, port=443, protocol="https")
/home/dell/.pyenv/versions/3.9.4/lib/python3.9/site-packages/urllib3/connectionpool.py:1013: InsecureRequestWarning: Unverified HTTPS request is being made to host '10.114.2.62'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
>>> from requests.packages import urllib3
>>> urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
>>> c.get('/v2')
'{"environments":"/api/v2/environments/","groups":"/api/v2/groups/","jobs":"/api/v2/jobs/","orders":"/api/v2/orders/","recurring-jobs":"/api/v2/recurring-jobs/","resource-handlers":"/api/v2/resource-handlers/","servers":"/api/v2/servers/","blueprints":"/api/v2/blueprints/","resources":"/api/v2/resources/","resource-types":"/api/v2/resource-types/","users":"/api/v2/users/","os-builds":"/api/v2/os-builds/","applications":"/api/v2/applications/","actions":"/api/v2/actions/","orchestration-actions":"/api/v2/orchestration-actions/","server-actions":"/api/v2/server-actions/","resource-actions":"/api/v2/resource-actions/","rules":"/api/v2/rules/"}'

 

Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.