Last active
January 7, 2019 08:01
-
-
Save xbns/ef48ed0d6850db2fb77ce8a60595c5c6 to your computer and use it in GitHub Desktop.
search user given api endpoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
import csv | |
token = '' | |
program_id = '' | |
def get_auth_token(token,program_id): | |
endpoint = 'https://xxx.mycompany.yy/auth/login' | |
payload = { | |
'username': '+25472xxxxxxx', # change this! | |
'password': 'xxxxxxxxxxx',# your password | |
'grant_type':'password', | |
'client_id' : 'web_app' | |
} | |
headers = { | |
'Authorization': token, | |
'programId': program_id | |
} | |
response = requests.post(endpoint,headers=headers, data=payload) | |
# For successful API call, response code will be 200 (OK) | |
if(response.ok): | |
jData = json.loads(response.content) | |
program_id = jData['payload']['user']['ownerProgramId'] | |
for key in jData: | |
if key == 'access_token' in jData: | |
#print(str(jData[key])) # cast type object to string | |
token='Bearer'+' '+str(jData[key]) | |
#print(token) | |
#print('\n') | |
#print(program_id) | |
return [token,program_id]; | |
else: | |
# If response code is not ok (200), print the resulting http error code with description | |
raise ApiError('Cannot fetch access token: {}'.format(response.status_code)) | |
# search for user using their phone numbers,extract their national id export the data into a csv | |
# | |
def list_users_csv(token,program_id): | |
token,program_id = get_auth_token(token,program_id) | |
headers = { | |
'Authorization': token, | |
'programId': program_id | |
} | |
csvFile1 = 'phone-numbers.csv' | |
csvFile2 = 'msisdn-with-ids.csv' | |
with open(csvFile1,'r')as readFile: | |
reader = csv.reader(readFile) | |
next(reader) # skip header | |
for row in reader: | |
params ={'q': row[0]} | |
endpoint = "https://xxx.mycompany.yy/user/search" | |
response = requests.get(endpoint,headers=headers,params=params) | |
if(response.ok): | |
jsonObjectInfo = json.loads(response.content) | |
with open(csvFile2,'a',newline='') as writeFile: | |
filewriter = csv.writer(writeFile) | |
for eachJsonObject in jsonObjectInfo['data']: | |
phone_no = eachJsonObject['msisdn'] | |
national_id = eachJsonObject['nationalId'] | |
eachJsonObject = [phone_no,national_id] | |
print(eachJsonObject) | |
filewriter.writerow(eachJsonObject) | |
writeFile.close() | |
else: | |
response.raise_for_status() | |
readFile.close() | |
if __name__ == "__main__": | |
list_users_csv(token,program_id) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment