Quickstart tutorial
This guide provides a step-by-step tutorial on how to transfer files by making HTTPS API requests to CFT.
Note: The sample code provided is currently only available in Python 3.
Prerequisites
- You need to complete the admin portal setup and whitelisting requirements.
- You need to install Python 3 and know how to set up libraries.
Initial setup
Follow these steps:
- Create a new folder for your file transfer. For example, name your folder:
transfer-quickstart. - From your terminal, set the directory to the new folder. For example, use the command:
cd transfer-quickstart.
Authentication
To obtain an auth token, follow these steps:
Important: The sample codes provided are not meant for use in Production environment. You should use the samples as a guide on handling keys and secrets safely.
Create a file for authentication. For example:
login.py.Copy the following code into the
login.pyfile.from base64 import b64encode, decode import http.client import json # Replace with your app_id and api_secrets, workflow_id and server api_id = 'YOUR_APP_ID' api_secret = 'YOUR_APP_SECRET' workflow_id = 'YOUR_WORKFLOW_ID' payload = '' # Leave this blank server = 'API Server' # The DNS name of the CFT API Server, not URI # Set up the credentials for the login request cred = api_id+":"+api_secret # Create a Base64 encoded string using the api_id and api_secret b64cred = b64encode(cred.encode("ascii")).decode("ascii") # Set up the headers for the requests. You will need # the workflow ID and the base64 encoded credentials to authenticate headers = { 'Content-Type': 'application/json', # You can change the name of the User Agent to your own app name 'User-Agent': 'QuickStartClient/0.0.1', 'workflowID': workflow_id, 'Authorization': 'Basic %s' % b64cred } # Make a connection to the API server conn = http.client.HTTPSConnection(server) # Perform the login request with the headers conn.request("POST", "/v2/auth?application_type=backend", payload, headers) # Get the response res = conn.getresponse() # Read the response data if res.status == 200: # Login is ok data = res.read() # Convert the data to a json object data = json.loads(data.decode("utf-8")) # Get the token from the response token = data['access_token'] # Print the token print('Success: %s' % token) else: print("Error: %s" % res.status) print(res.read())Replace the following placeholders in the code with the correct values.
Placeholder Description api_idThe Client ID of your HTTPS application. api_secretThe Client Secret of your HTTPS application. workflow_idYour workflow ID. serverThe DNS name of the CFT API server.
https://api.cft.stack.gov.sg (Internet)
https://api.in.cft.stack.gov.sg (Intranet)Run the command:
python3 login.py.Retrieve the auth token from the output.
If the request is successful, you should see
"Success: <token>"in the response. Copy the<token>value. This is your auth token.If the request fails, you will receive an error in the response similar to the sample below. Confirm that your credentials are correct and try again.
Error: 403 b'{"error":"Not Authorised","message":"Application not authorised to access given WorkflowID","statusCode":403}'
Send files
To send or upload a file, follow these steps:
Important: The sample codes provided are not meant for use in Production environment. You should use the samples as a guide on handling keys and secrets safely.
Create a file for sending
send.py.Copy the following code into the
send.pyfile.from base64 import b64encode, decode import http.client import json # This sample code provides authentication and sending of a file def send_csv_file(bearer: str, workflowid: str, filename: str, payload: str, unique: bool, server: str)->str: conn = http.client.HTTPSConnection(server) headers = { 'Authorization': 'Bearer %s' % bearer, 'User-Agent': 'QuickStartClient/0.0.1', 'Content-Type': 'text/plain', 'x-cft-do-not-overwrite': str(unique) } resource = "/v2/workflows/%s/files/space+%s.csv" % (workflowid, filename) conn.request( "PUT", resource, payload, headers) res = conn.getresponse() print("response status of file sent: %s" % res.status) # this is the HTTP status code of the response if res.status == 201 : return res.getheader("X-Cft-File-Id") else: print(res.status) return "" # Replace with your api_id and api_secrets, workflow_id and server api_id = 'YOUR_APP_ID' api_secret = 'YOUR_APP_SECRET' workflow_id = 'YOUR_WORKFLOW_ID' payload = '' # leave this blank server = 'api server' # DNS name of the API server, not URI # Sets up the credentials for the login request cred = api_id+":"+api_secret # Creates a Base64 encoded string using the api_id and api_secret b64cred = b64encode(cred.encode("ascii")).decode("ascii") # Sets up the headers for the requests. You will need # the workflow id and the base64 encoded credentials to authenticate headers = { 'Content-Type': 'application/json', # you can change the name of the User Agent to your own app name 'User-Agent': 'QuickStartClient/0.0.1', 'workflowID': workflow_id, 'Authorization': 'Basic %s' % b64cred } # Makes a connection to the API server conn = http.client.HTTPSConnection(server) # Performs the login request with the headers conn.request("POST", "/v2/auth?application_type=backend", payload, headers) # Get the response res = conn.getresponse() # Read the response data if res.status == 200: # login is ok data = res.read() # convert the data to a json object data = json.loads(data.decode("utf-8")) # get the token from the response token = data['access_token'] # print the token # Add this call, this sends a file to CFT result = send_csv_file(token,workflow_id, 'hello.csv', # This is the file name 'hello world', # This is the content of the file True, # for REST APIs set this to true server) print("FileID: "+result) # take note of file ID, each send will create a new file ID, this is used to retrieve the file later else: print("Error: %s" % res.status) print(res.read())Replace the following placeholders in the code with the correct values.
Placeholder Description api_idThe Client ID of your HTTPS application. api_secretThe Client Secret of your HTTPS application. workflow_idYour workflow ID. serverThe DNS name of the CFT API server.
https://api.cft.stack.gov.sg (Internet)
https://api.in.cft.stack.gov.sg (Intranet)Run the command:
python3 send.py.Retrieve the File ID from the output.
If the request is successful, you should see
"FileID: <file ID>"in the response. Copy the<file ID>value. This is used to retrieve or download the file from the CFT server.
Receive files
To receive or download a file, follow these steps:
Important: The sample codes provided are not meant for use in Production environment. You should use the samples as a guide on handling keys and secrets safely.
Create a file for receiving
receive.py.Copy the following code into the
receive.pyfile.from base64 import b64encode, decode import http.client import json # This sample code provides authentication and receiving of a file def receive_csv_file(bearer: str, workflowid: str, fileid: str, server: str)->str: conn = http.client.HTTPSConnection(server) payload = '' headers = { 'Content-Type': 'application/octet-stream', 'User-Agent': 'QuickStartClient/0.0.1', 'Authorization': 'Bearer %s' % bearer, } resource = ("/v2/files/%s/download" % fileid) # endpoint to download file conn.request("GET", resource, payload, headers) res = conn.getresponse() print("Response: %s" % res.status) # the HTTP status code of the file API download endpoint # check if response is 200 if res.status == 200: data = res.read() print(data.decode("utf-8")) else: print(res.status) sys.exit(1) # Replace with your api_id and api_secrets, workflow_id and server api_id = 'YOUR_APP_ID' api_secret = 'YOUR_APP_SECRET' workflow_id = 'YOUR_WORKFLOW_ID' payload = '' # leave this blank fileid = '' # fileid of the file to be downloaded server = 'api server' # DNS name of the API server, not URI # Sets up the credentials for the login request cred = api_id+":"+api_secret # Creates a Base64 encoded string using the api_id and api_secret b64cred = b64encode(cred.encode("ascii")).decode("ascii") # Sets up the headers for the requests, you will need # the workflow id and the base64 encoded credentials to authenticate headers = { 'Content-Type': 'application/json', # You can change the name of the User Agent to your own app name 'User-Agent': 'QuickStartClient/0.0.1', 'workflowID': workflow_id, 'Authorization': 'Basic %s' % b64cred } # Makes a connection to the API server conn = http.client.HTTPSConnection(server) # Performs the login request with the headers conn.request("POST", "/v2/auth?application_type=backend", payload, headers) # Gets the response res = conn.getresponse() # Reads the response data if res.status == 200: # login is ok data = res.read() # convert the data to a json object data = json.loads(data.decode("utf-8")) # get the token from the response token = data['access_token'] # print the token # Add this call, this sends a file to CFT result = receive_csv_file(token, workflow_id, fileid, server) else: print("Error: %s" % res.status) print(res.read())Replace the following placeholders in the code with the correct values.
Placeholder Description api_idThe Client ID of your HTTPS application. api_secretThe Client Secret of your HTTPS application. workflow_idYour workflow ID. serverThe DNS name of the CFT API server.
https://api.cft.stack.gov.sg (Internet)
https://api.in.cft.stack.gov.sg (Intranet)Run the command:
python3 receive.py. If the request is successful, you should see the HTTP status response and the file payload.