Creating API User and Key With Python
If you are looking to leverage the MoMo Open APIs for your business, one of the foremost steps is to create an API user and API Key
this guide, we will walk you through the process of creating an API user and generating an API key using Python. Follow the steps below and run the provided Python script to initiate your integration.
Step-by-Step Guide
- Install Required Libraries:
You'll need the
requests
anduuid
libraries. Install them using:pip install requests uuid
- Set Up Environment Variables:
Configure the environment variables for your subscription keys. This setup will streamline the integration process.
- Execute the Python Script:
Use the script below to create an API user and generate an API key:
# Import necessary libraries
import requests as rq
import json
import uuid
# Set endpoint URL and headers
url = "https://sandbox.momodeveloper.mtn.com/v1_0/apiuser"
API_USER = str(uuid.uuid4())
headers = {
"X-Reference-Id": API_USER,
"Ocp-Apim-Subscription-Key": "4c91dae7a6f1474387a23a1f3d448eb7",
"Content-Type": "application/json"
}
# Define the body
body = {
"providerCallbackHost": "webhook.site"
}
# Send POST request to create API user
resp = rq.post(url, json=body, headers=headers)
# Set endpoint URL for generating API key
url = "https://sandbox.momodeveloper.mtn.com/v1_0/apiuser/"+API_USER+"/apikey"
headers = {
"Ocp-Apim-Subscription-Key": "4c91dae7a6f1474387a23a1f3d448eb7",
"Content-Type": "application/json"
}
# Send POST request to generate API key
resp = rq.post(url, headers=headers)
print(resp.status_code, "\nAPI User is", API_USER)
json_resp = json.loads(resp.text)
API_KEY = json_resp.get("apiKey", "")
print("API Key is", API_KEY)
Understanding the Script
The script performs the following actions:
- Imports the necessary libraries:
requests
,json
, anduuid
. - Sets the endpoint URL and headers required for API requests.
- Generates a unique API user ID using UUID.
- Defines the callback host in the body of the request.
- Sends a POST request to create the API user and prints the status code and API user ID.
- Sends another POST request to generate an API key for the created API user and prints the API key.
Once you have the API User and API Key, you can proceed to integrate with the MoMo APIs according to your business needs.
Helpful Resources
Join the MoMo community to ask questions, learn, collaborate, and share ideas. Inclusion means no one is left behind, and together we can enhance each other’s journeys. Happy coding!