Retrieve token

 To retrieve the token from the API using Python (similar to the PowerShell command), you can use the requests library in Python. Below is a step-by-step explanation and code example of how to achieve this in Visual Studio Code.

Step 1: Install Required Libraries

First, ensure you have the requests library installed. Open the terminal in Visual Studio Code and run:

bash
pip install requests

Step 2: Write the Python Script to Retrieve the Token

Here’s how you can write a Python script that replicates the functionality of the PowerShell command you shared:

python
import requests import json # Define the API endpoint url = "https://dev-api.cmnow-dev.ubsdev.net/login" # Define the payload (data to send in the POST request) payload = { 'user': 'SVC_SN_DEV_AT16933', 'password': 'Fy7y!5uw41J3f5dG8ic2f14Be3Wo7B' } # Define the headers (Content-Type is JSON) headers = { 'Content-Type': 'application/json' } # Send the POST request response = requests.post(url, data=json.dumps(payload), headers=headers) # Check if the request was successful if response.status_code == 200: # Convert the response to JSON format response_data = response.json() # Extract the token from the response token = response_data.get('token') # Print the token print(f"Token: {token}") # Optionally, you can store the token in a variable for later use else: print(f"Failed to retrieve token. Status Code: {response.status_code}") print(response.text)

Step 3: Run the Script

  1. Save the script as retrieve_token.py in Visual Studio Code.

  2. Open the integrated terminal in VS Code (press Ctrl + ).

  3. Run the script by executing the following command:

    bash
    python retrieve_token.py

Explanation of the Code:

  1. API Endpoint: The url variable contains the endpoint where the login request is sent.
  2. Payload: The payload dictionary holds the user credentials (username and password) to be sent in the POST request body.
  3. Headers: The headers dictionary specifies the content type as JSON.
  4. POST Request: The requests.post() method sends the login request to the API, and the response is captured.
  5. Response Handling: If the request is successful (status_code == 200), the token is extracted and printed.

Step 4: Verify the Output

After running the script, the token will be printed in the terminal, similar to how you retrieved it in PowerShell:

bash
Token: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx

Optional: Store the Token for Later Use

If you need to use this token in another script (like making further API calls), you can store it in a file or a variable. For example:

python
with open("token.txt", "w") as token_file: token_file.write(token)

This will store the token in a text file (token.txt) that you can use in subsequent scripts. Let me know if you need further adjustments!

No comments

Theme images by tjasam. Powered by Blogger.