Articles on: Discord Bot Hosting

How to use the Pterodactyl API using JS

How to use the Pterodactyl API using JS



Firstly, we need to create an API key. We will need this to interact with the panel. To do this, Click “API Credentials” on the left-hand side of the panel.

Set the description and the Allowed IPs. This is useful if you would like to secure the usage of the API key. Leave it blank if you would like to allow any IP address to the API key.



The API key is now shown.

Note: Keep a backup of your API key. You will not be able to see it after you close this box!



We are now ready to start coding! You will require an HTTP library. In this case, we are going to use axios. You are able to view all the pterodactyl endpoints here. Please note that the documentation page is not official!

In this example, We will cover the most useful endpoints.

How to check server info

To check the server status, you will need to make a request to /api/client/servers/<server id>. Of course, replace <server id> with your server id.

Here is an example of a request:

const axios = require('axios');


const apiKey = 'My API Key'

axios.get('https://control.sparkedhost.us/api/client/servers/<server Id>, {
    headers: {
        'Accept': 'application/json',
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + apiKey
    }
}).then(function (response) {
    console.log(response);
  }).catch(function (error) {
    console.log(error);
  })


This is the response we get back from the panel:



How to receive live server stats (e.g console input, status)

For this, you will need to use another library called ws. Pterodactyl uses sockets to send and receive live data. You are able to use the following code:

const axios = require('axios');
const WebSocket = require('ws')

const apiKey = 'zvVLw6PAenoTczUyJTa2XPZYXiQHZ8DYkZwnmuKz7kcFZIF0';

axios.get('https://control.sparkedhost.us/api/client/servers/f7a7faee/websocket', {
    headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + apiKey,
        }
    }).then(function (response) {
        const token = response.data.data.token;
        const ws = new WebSocket(response.data.data.socket);

        ws.on('open', function open() {
            ws.send(JSON.stringify({"event":"auth","args":[token]}));
          });
          
        ws.on('message', function message(data) {
            console.log(data);
        });
          
        ws.on('error', function error(err) {
            console.log(err);
        });
    }).catch(function (error) {
        console.log(error);
    });


This is the response we get back:



View more about web socket requests here.


If you require any further assistance, please create a ticket here.


Created By: Greg K.

Updated on: 24/11/2022

Was this article helpful?

Share your feedback

Cancel

Thank you!