In this guide, we're going to build a python script that API clients built from our OpenAPI specification file. The tool used below to generate the client, openapi-generator, supports many different programming languages, not just python.
If you're not already familiar with how to use OpenAPI specification files to generate clients or how to install and use them, LLMs like ChatGPT can be very helpful with navigating the unique aspects and build tools for your programming language.
Create Your KORE API Client Resource
To make requests to the KORE REST APIs, you need to first create a Client resource in the KORE Developer Portal. Note this is different than the "clients" that we'll be generating from the OpenAPI specification file and will be using to make requests to the APIs. You get your necessary credentials by creating this Client resource.
KORE's API's follow OAuth2 for authenticating to the APIs. You'll create a Client that includes Super SIM within its scoped products and then use the ID and secret of the Client to generate an access token that you'll include in your request headers to authenticate to the API endpoints.
Learn more about how to generate this Client to use with Super SIM . You can jump to "Get Started!" section for the steps to create your Client. Once you have your client ID and secret return here.
Your client secret will only be shown to you once so be sure to save it somewhere. Don't worry though, if you lose it you can always generate a new Client or refresh your secret.
Generating Your Local Client
There are many options you can choose from for to generate API clients from OpenAPI specification files. How you then use the generated clients will vary significantly from tool to tool. For this guide we'll be using the openapi-generator CLI tool.
First, install the openapi-generator CLI tool.
brew install openapi-generator
Next, download a copy the Super SIM OpenAPI specification file from Github and save it in your project directory.
Generate a python client using the OpenAPI specification file and the generator tool.
Create a python virtual environment to which you'll install your packages including your generated client.
python3 -m venv ./env
Activate the virtual environment.
source env/bin/activate
Install the package locally in your virtual environment.
pip3 install ./clients/kore_supersim_client
With that done, let's generate a file called client-test.py and make sure that we can successfully import the installed client and run the code without errors.
from supersim_client import ApiClient, Configurationdefmain():print("hello world")if__name__=="__main__":main()
Run your code.
python3 client-test.py
If you see "hello world" successfully logged with no errors, then you should be all set to begin making API requests with your generated and installed client. We'll be doing all coding for this guide in the client-test.py file.
Install Other Dependencies
pip3 install requests
Authenticating to the KORE REST API
To access the KORE REST APIs, we'll need an access token. We'll use the client ID and secret from the Client resource you created earlier to generate a temporary token used to authenticate your requests.
We'll add a function to our code to get a token with our secrets and use it to print out the some useful properties from the access token response. Replace <YOUR_CLIENT_ID> and <YOUR_CLIENT_SECRET> with your unique credentials.
Treat your client ID, secret, and access tokens like they are passwords. Do not share them with anyone and never commit them to any public code repositories.
Access tokens are temporary. You can see how many seconds the token is valid for by checking the expires_in property the response. If you use an expired token, your requests will be rejected. When you get a new token, you'll need to regenerate the clients with a new configuration that has the updated token. We recommend creating a class that manages refreshing the token and regenerating the clients that wraps around the generated client resources in a production setting where your code is deployed and running on servers versus writing simple scripts like we are here.
Generate API Client Instances for Each Endpoint
Now, we'll use our access token to begin generating instances of our API clients, one for each endpoint we'll be making requests to. Note that there is a module to be imported for each endpoint that you'll use to generate a client for that endpoint.
from supersim_client import ApiClient, Configuration, SupersimV1SimApi, SupersimV1FleetApiimport requestsTOKEN_URL ="https://api.korewireless.com/api-services/v1/auth/token"CLIENT_ID='<YOUR_CLIENT_ID>'CLIENT_SECRET='<YOUR_CLIENT_SECRET>'defget_access_token(client_id,client_secret,token_url): response = requests.post(token_url, data={'grant_type': 'client_credentials','client_id': client_id,'client_secret': client_secret }) token_data = response.json()return token_datadefmain(): token_data =get_access_token(CLIENT_ID, CLIENT_SECRET, TOKEN_URL) access_token = token_data['access_token'] config =Configuration( access_token=access_token # Set your OAuth2 token here )# Generate base API client passed to each endpoint client api_client =ApiClient(config)# Generate clients for each endpoint sim_api_client =SupersimV1SimApi(api_client) fleet_api_client =SupersimV1FleetApi(api_client)if__name__=="__main__":main()
You can use the clients generated for each endpoint to list out your Sims and Fleet resources.
from supersim_client import ApiClient, Configuration, SupersimV1SimApi, SupersimV1FleetApiimport requestsTOKEN_URL ="https://api.korewireless.com/api-services/v1/auth/token"CLIENT_ID='<YOUR_CLIENT_ID>'CLIENT_SECRET='<YOUR_CLIENT_SECRET>'defget_access_token(client_id,client_secret,token_url): response = requests.post(token_url, data={'grant_type': 'client_credentials','client_id': client_id,'client_secret': client_secret }) token_data = response.json()return token_datadefmain(): token_data =get_access_token(CLIENT_ID, CLIENT_SECRET, TOKEN_URL) access_token = token_data['access_token'] config =Configuration( access_token=access_token # Set your OAuth2 token here )# Generate base API client passed to each endpoint client api_client =ApiClient(config)# Generate clients for each endpoint sim_api_client =SupersimV1SimApi(api_client) fleet_api_client =SupersimV1FleetApi(api_client) sims_response = sim_api_client.list_sim() fleets_response = fleet_api_client.list_fleet()print(sims_response.sims)print(fleets_response.fleets)if__name__=="__main__":main()
Go ahead and run your code.
Assuming you already have SIMs and Fleets created on your account, you should see arrays of these resources printed out when you run your code. If you have more than the default page size (50) of either resource though, these results are incomplete. That's because the results are just one page. You can increase the page_size up to 1,000 if you have less than 1,000 resources, but to properly scale this out, we'll need to use the pagination information in our responses to fetch all the pages of results we need.
Here's an example of how you could write a function to fetch all pages of Sim resources:
from clients.kore_supersim_client.build.lib.supersim_client.models.sim_enum_status import SimEnumStatusfrom urllib.parse import urlparse, parse_qsdeffetch_all_sims(sim_api_client: SupersimV1SimApi,status: SimEnumStatus=None,fleet:str=None): accumulated_sims = [] next_page_url =None first_page_response = sim_api_client.list_sim(status=status,fleet=fleet) accumulated_sims += first_page_response.simsif first_page_response.meta.next_page_url isnotNone: next_page_url = first_page_response.meta.next_page_urlwhile next_page_url isnotNone:# Parse the next page URL string so we can pass in the individual properties# when fetching the next page. parsed_next_page_url =urlparse(next_page_url) query_params =parse_qs(parsed_next_page_url.query) query_params ={key: value[0]for key, value in query_params.items()} next_page_response = sim_api_client.list_sim( status=status, fleet=fleet, page=int(query_params['Page']), page_size=int(query_params['PageSize']), page_token=query_params['PageToken'] ) next_page_sims = next_page_response.sims accumulated_sims += next_page_sims# Reassign the variable to continue or break the loop. next_page_url = next_page_response.meta.next_page_urlreturn accumulated_sims
Note that in the example above, the status variable is using a type also imported from our generated code. Finding and importing these types can be much easier if you use an IDE such as PyCharm in our case here. The generated client resource will be expecting specific types for its arguments.
We can now use this function in our main()call to get all of our Sims if we needed to iterate over each one to pull data usage data for each or build CSV export.
defmain(): token_data =get_access_token(CLIENT_ID, CLIENT_SECRET, TOKEN_URL) access_token = token_data['access_token'] config =Configuration( access_token=access_token # Set your OAuth2 token here )# Generate base API client passed to each endpoint client api_client =ApiClient(config)# Generate clients for each endpoint sim_api_client =SupersimV1SimApi(api_client) fleet_api_client =SupersimV1FleetApi(api_client) all_sims =fetch_all_sims(sim_api_client)print(all_sims)print(len(all_sims))
Bringing It All Together
Now that we can fetch all of our Sims, we can build upon our script here to build a practical application that you can use easily pull data about all of your SIMs and data usage for the last 30 days.
First, we'll create a similar function to like we did for our Sim resources to fetch all of our Fleet resources.
Next, we're going to generate another endpoint client for the UsageRecords endpoint.
Lastly, we'll iterate over each SIM and pull the SIM's usage and build a CSV report.
import requestsfrom urllib.parse import urlparse, parse_qsimport csvfrom supersim_client import ApiClient, Configuration, SupersimV1SimApi, SupersimV1FleetApifrom clients.kore_supersim_client.build.lib.supersim_client.models.sim_enum_status import SimEnumStatusfrom clients.kore_supersim_client.build.lib.supersim_client.models.supersim_v1_fleet import SupersimV1Fleetfrom clients.kore_supersim_client.build.lib.supersim_client.models.supersim_v1_sim import SupersimV1Simfrom clients.kore_supersim_client.supersim_client.api.supersim_v1_usage_record_api import SupersimV1UsageRecordApifrom clients.kore_supersim_client.supersim_client.models.usage_record_enum_granularity import UsageRecordEnumGranularityTOKEN_URL ="https://api.korewireless.com/api-services/v1/auth/token"CLIENT_ID='<YOUR_CLIENT_ID>'CLIENT_SECRET='<YOUR_CLIENT_SECRET>'defget_access_token(client_id,client_secret,token_url): response = requests.post(token_url, data={'grant_type': 'client_credentials','client_id': client_id,'client_secret': client_secret }) token_data = response.json()return token_datadeffetch_all_sims(sim_api_client: SupersimV1SimApi,status: SimEnumStatus=None,fleet:str=None): accumulated_sims = [] next_page_url =None first_page_response = sim_api_client.list_sim(status=status,fleet=fleet) accumulated_sims += first_page_response.simsif first_page_response.meta.next_page_url isnotNone: next_page_url = first_page_response.meta.next_page_urlwhile next_page_url isnotNone:# Parse the next page URL string so we can pass in the individual properties# when fetching the next page. parsed_next_page_url =urlparse(next_page_url) query_params =parse_qs(parsed_next_page_url.query) query_params ={key: value[0]for key, value in query_params.items()} next_page_response = sim_api_client.list_sim( status=status, fleet=fleet, page=int(query_params['Page']), page_size=int(query_params['PageSize']), page_token=query_params['PageToken'] ) next_page_sims = next_page_response.sims accumulated_sims += next_page_sims# Reassign the variable to continue or break the loop. next_page_url = next_page_response.meta.next_page_urlreturn accumulated_simsdeffetch_all_fleets(fleet_api_client: SupersimV1FleetApi): accumulated_fleets = [] next_page_url =None first_page_response = fleet_api_client.list_fleet() accumulated_fleets += first_page_response.fleetsif first_page_response.meta.next_page_url isnotNone: next_page_url = first_page_response.meta.next_page_urlwhile next_page_url isnotNone:# Parse the next page URL string so we can pass in the individual properties# when fetching the next page. parsed_next_page_url =urlparse(next_page_url) query_params =parse_qs(parsed_next_page_url.query) query_params ={key: value[0]for key, value in query_params.items()} next_page_response = fleet_api_client.list_fleet( page=int(query_params['Page']), page_size=int(query_params['PageSize']), page_token=query_params['PageToken'] ) next_page_fleets = next_page_response.fleets accumulated_fleets += next_page_fleets# Reassign the variable to continue or break the loop. next_page_url = next_page_response.meta.next_page_urlreturn accumulated_fleetsdefmain(): token_data =get_access_token(CLIENT_ID, CLIENT_SECRET, TOKEN_URL) access_token = token_data['access_token'] config =Configuration( access_token=access_token # Set your OAuth2 token here )# Generate base API client passed to each endpoint client api_client =ApiClient(config)# Generate clients for each endpoint sim_api_client =SupersimV1SimApi(api_client) fleet_api_client =SupersimV1FleetApi(api_client) usage_records_client =SupersimV1UsageRecordApi(api_client) all_sims: list[SupersimV1Sim]=fetch_all_sims(sim_api_client) all_fleets: list[SupersimV1Fleet]=fetch_all_fleets(fleet_api_client)# Build dictionary of Fleets for looking it up later. fleets_dict ={fleet.sid: fleet for fleet in all_fleets} output_file ="sim_usage_report.csv"withopen(output_file, mode="w", newline="")as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(["SIM SID","ICCID", "SIM Unique Name", "SIM Status", "Fleet SID", "Fleet Unique Name", "Fleet Data Limit (MBs)", "Data Used (MBs)"])for sim in all_sims: fleet_sid = sim.fleet_sid fleet = fleets_dict.get(fleet_sid) fleet_unique_name = fleet.unique_name if fleet else"Unknown" fleet_data_limit = fleet.data_limit if fleet else"Unknown" sim_usage_records = usage_records_client.list_usage_record( sim=sim.sid, granularity=UsageRecordEnumGranularity("all") ) data_used = sim_usage_records.usage_records[0].data_total data_used_mb = data_used / (1000*1000) csvwriter.writerow([ sim.sid, sim.iccid, sim.unique_name, sim.status, fleet_sid, fleet_unique_name, fleet_data_limit, data_used_mb ])if__name__=="__main__":main()
If you run your code, you should see the generated CSV in your project directory with information about each SIM and its usage.