How to get an API token and authorization in REST with Python

This guide shows how to log in to an application using REST and get an API token to authenticate yourself in Python. 

If you are using Postman or GpsGate REST API GUI, please read how to use REST API with Postman and GpsGate REST API GUI. 

Prerequisites

Obtaining the API token

To get the API token for a user, an HTTP POST request should be sent to the Token resource. In the post body, username and password are specified in JSON format, and the response body contains a token key with an actual API Token as the value. The token should be used in an HTTP Authorization header while communicating with other resources.

A login request consists of the following structure:

http://{hostname}:{port}/comGpsGate/api/v.1/applications/{applicationid}/tokens

  • {hostname} is where your GpsGate Server is installed.
  • {port} port number (the default port is 80).
  • {applicationid} is the ID of the application you are trying to log into.

You can find your application ID in Site Admin:

mceclip0.png

Example

  • Server IP: 192.168.0.34
  • Port: 80
  • Application ID: 40

Using Python, we'll make a request to the following URL with headers

http://192.168.0.34:80/comGpsGate/api/v.1/applications/40/tokens where GpsGate is installed to the default port and the application Id 40.  

Here is the sample code: 

import json
import requests

URL = "http://192.168.0.34/comGpsGate/api/v.1/applications/40/tokens"

headers = {
"accept": "application/json",
"Content-Type": "application/json"
}

params = {
"username": "your user name",
"password": "your password"
}

resp = requests.post(URL, headers = headers ,data=json.dumps(params))
tk = json.loads(resp.text)['token']

if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('token: ' + str(tk))
print('Success')

 

Now we get the token and save it in variable tk. 

Authorizing use of the token

To send an authorization request to GpsGate REST API, you need to select the GET method with an authorization key (the token obtained previously), as in the sample code below.

Sample of loading a user list with REST:

url1 = "http://192.168.0.34/comGpsGate/api/v.1/applications/40/users?FromIndex=0&PageSize=1000"

headers = {
"accept" : "application/json",
"Authorization": str(tk)
}

resp = requests.get(url1, headers=headers)

if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('User List Loaded Successfully')