API call examples 2019-07-18T10:55:18+08:00

API Call Examples

This page shows sample requests to open data API using popular programming languages.

Java or Android (Java) with Jersey Client:

1. Dependencies

  • Maven
  org.glassfish.jersey.core
  jersey-client
  2.27


  org.glassfish.jersey.media
  jersey-media-json-jackson
  2.27


  org.glassfish.jersey.inject
  jersey-hk2
  2.27


  org.glassfish.jersey.security
  oauth2-client
  2.27


    com.fasterxml.jackson.core
    jackson-core
    2.9.6


    com.fasterxml.jackson.core
    jackson-annotations
    2.9.6


    com.fasterxml.jackson.core
    jackson-databind
    2.9.6
  • gradle
implementation 'org.glassfish.jersey.core:jersey-client:2.27'
implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:2.27'
implementation 'org.glassfish.jersey.inject:jersey-hk2:2.27'
implementation 'org.glassfish.jersey.security:oauth2-client:2.27'
implementation 'com.fasterxml.jackson.core:jackson-core:2.9.6'
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.9.6'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.6'

2. Define a HALWrapper class

public class ComputerRoomPC {
  private String name;
  private int x;
  private int y;
  private boolean available;
  
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getX() {
    return x;
  }
  public void setX(int x) {
    this.x = x;
  }
  public int getY() {
    return y;
  }
  public void setY(int y) {
    this.y = y;
  }
  public boolean isAvailable() {
    return available;
  }
  public void setAvailable(boolean available) {
    this.available = available;
  }
}

public class ComputerRoomPCStatus {
  private String _id;
  private String buildingCode;
  private String roomNo;
  private Date lastUpdate;
  private List pc;
  public String get_id() {
    return _id;
  }
  public void set_id(String _id) {
    this._id = _id;
  }
  public String getBuildingCode() {
    return buildingCode;
  }
  public void setBuildingCode(String buildingCode) {
    this.buildingCode = buildingCode;
  }
  public String getRoomNo() {
    return roomNo;
  }
  public void setRoomNo(String roomNo) {
    this.roomNo = roomNo;
  }
  public Date getLastUpdate() {
    return lastUpdate;
  }
  public void setLastUpdate(Date lastUpdate) {
    this.lastUpdate = lastUpdate;
  }
  public List getPc() {
    return pc;
  }
  public void setPc(List pc) {
    this.pc = pc;
  }
}

public class ComputerRoomPCStatusHALWrapper {

  private List _embedded;
  private int _returned;

  public List get_embedded() {
    return _embedded;
  }
  public void set_embedded(List _embedded) {
    this._embedded = _embedded;
  }
  public int get_returned() {
    return _returned;
  }
  public void set_returned(int _returned) {
    this._returned = _returned;
  }
}

3. Get the data

ClientConfig clientConfig = new ClientConfig();
clientConfig.register(OAuth2ClientSupport.feature("3b07f192-c29f-34d5-8bfc-1c74ccbeebe1"));
Client client = ClientBuilder.newClient(clientConfig);

ComputerRoomPCStatusHALWrapper response = client
      .target("https://api.data.um.edu.mo/service/facilities/computer_room_pc_status/v1.0.0")
      .path("/all")
      .request(MediaType.APPLICATION_JSON)
      .get(ComputerRoomPCStatusHALWrapper.class);

// response.get_embedded() is your data

Android (Kotlin) with Jersey Client:

1. Dependencies

implementation 'org.glassfish.jersey.core:jersey-client:2.27'
implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:2.27'
implementation 'org.glassfish.jersey.inject:jersey-hk2:2.27'
implementation 'org.glassfish.jersey.security:oauth2-client:2.27'
implementation 'com.fasterxml.jackson.core:jackson-core:2.9.6'
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.9.6'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.6'

2. Define a HALWrapper class

class ComputerRoomPC {
    var name: String? = null
    var x: Int = 0
    var y: Int = 0
    var isAvailable: Boolean = false
}

class ComputerRoomPCStatus {
    var _id: String? = null
    var buildingCode: String? = null
    var roomNo: String? = null
    var lastUpdate: Date? = null
    var pc: List? = null
}

class ComputerRoomPCStatusHALWrapper {

    var _embedded: List? = null
    var _returned: Int = 0
}

3. Get the data

      val clientConfig = ClientConfig()
      clientConfig.register(OAuth2ClientSupport.feature("3b07f192-c29f-34d5-8bfc-1c74ccbeebe1"))
      val client = ClientBuilder.newClient(clientConfig)

      val response : ComputerRoomPCStatusHALWrapper = client
              .target("https://api.data.um.edu.mo/service/facilities/computer_room_pc_status/v1.0.0")
              .path("/all")
              .request(MediaType.APPLICATION_JSON)
              .get(ComputerRoomPCStatusHALWrapper::class.java)		

// response._embedded() is your data
var http = require("https");

var options = {
  "method": "GET",
  "hostname": "api.data.um.edu.mo",
  "path": "/service/facilities/computer_room_pc_status/v1.0.0/all",
  "accept": "application/json",
  "headers": {
    "Authorization": "Bearer 3b07f192-c29f-34d5-8bfc-1c74ccbeebe1"
  }
};

var req = http.request(options, function(response) {
  var chunks = [];
  response.on("data", function(chunk) {
      chunks.push(chunk);
  });
  response.on("end", function() {
    var body = Buffer.concat(chunks);
    var data = JSON.parse(body);
    
    console.log(data); // Your data is here
  });
});
req.end();

Ensure python library “requests” is installed

import requests

url = 'https://api.data.um.edu.mo/service/facilities/computer_room_pc_status/v1.0.0/all'
response = requests.get(url, headers = { "Authorization": "Bearer 3b07f192-c29f-34d5-8bfc-1c74ccbeebe1" })
if response.status_code != 200:
  # Handle error here
  exit(1);
data = response.json();
# data['_embedded'] is your data

1. Ensure PHP has some extensions

  • json
  • phar
  • iconv

2. Make sure GIT is installed

3. Install GuzzleHTTP

curl -sS https://getcomposer.org/installer | php
php composer.phar require guzzlehttp/guzzle

4. Example

$client = new GuzzleHttp\Client(); 
$res = $client->request('GET', 'https://api.data.um.edu.mo/service/facilities/computer_room_pc_status/v1.0.0/all', [
'Accept' => 'application/json',
'headers' => [
	"Authorization" => "Bearer 3b07f192-c29f-34d5-8bfc-1c74ccbeebe1"
	]
]);

if ($res->getStatusCode() != 200) {
// Handle error
}

$data = json_decode($res->getBody());
// $data->_embedded is your data
let endpoint : String = "https://api.data.um.edu.mo/service/facilities/computer_room_pc_status/v1.0.0/all"
guard let url = URL(string: endpoint) else {
    print("Error: invalid URL")
    return
}

let sessionConfig = URLSessionConfiguration.default
sessionConfig.httpAdditionalHeaders = [ "Authorization": "Bearer 3b07f192-c29f-34d5-8bfc-1c74ccbeebe1" ]
let session = URLSession.init(configuration: sessionConfig)

let urlRequest = URLRequest(url: url)
let task = session.dataTask(with: urlRequest) {
    (data, response, error) in
    
    // Handle error
    guard error == nil else {
        print("Error: fail calling GET on " + endpoint + "!")
        print(error!)
        return
    }
    
    let statusCode = (response as? HTTPURLResponse)?.statusCode
    if statusCode != 200 {
        print("Error: status code is " + String(statusCode!) + " (expect 200)")
        return
    }
    
    // Handle the data
    guard let responseData = data else {
        print("Error: did not receive data")
        return
    }
    
    // Parse the data into json
    do {
        guard let jsonData = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else {
            print("Error: JSON stream is empty")
            return
        }
        
        // Your data is jsonData["_embedded"]
    } catch {
        print("Error: Unable to convert to JSON")
        return
    }
}
task.resume()
$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "https://api.data.um.edu.mo/service/media/events/v1.0.0/all",
        headers: {
            Authorization: 'Bearer b54b809c-392c-3758-9cd0-c9cb76302a98',
            Accept: 'application/json'
        },
        success: function(data) {
            console.log(data);
            console.log(data._embedded);
        }
    });
});