VGA Planets

Introduction

How The Website Works

Races

Dashboard

Starmap

Planets

Starships

General Information

Guides

Contributions

Searchable Documentation

Planets.nu Application Programming Interface (API)


Main Documentation —> How The Website Works —>API

Introduction
Programming Languages
API Detail
Example Calls
Table of API calls

Introduction

Planets.nu provides a number of API ( Application Programming Interface ) calls for developers to build in-game addons or standalone programs that can directly load, modify and save game data.

This is an advanced topic and regular Nu players do not need to understand or use API calls to play the game. If you have no experience in developing software then this is probably a topic area that you should avoid.

It is also important to note that the API does not grant developers any significant advantage. While the applications they write may process and present the data in new and hopefully better ways, they do not have access to additional information that normal players would not normally have available. The API calls just allow developers a way of accessing Nu data directly for their programs (rather than cutting and pasting from the screen).

Even if you are a developer working on a new addon you may not need to make any API calls. Most addons can access the game data it needs through the "vgap" object that the Nu client creates. This is usually a much easier way of accessing game information than having to resort to API calls. On the other hand, if you do have some experience in developing software then the Nu API calls may be useful to you.

Maybe you have an idea on how to better predict enemy ship movements. Maybe you have 30 other ideas you want to try out and see what is possible!

We currently have over 50 addons to the game and there is plenty more room for expansion. The sky really is the limit!

Programming languages

The API is accessible to any programming language that can access the Internet – meaning pretty much any modern language can be used. Many of the older languages may not be as suitable for Nu development and may need extensions to allow Internet access but even these would probably work OK.

The Planets.nu client is written in JavaScript and JQuery, as are most of the in-game addons created so far. We have provided a number of examples below, but if you are unsure which language to use then we would recommend JavaScript as the most common starting point.

You can create server side applications, usually web server applications, using languages such as Python, PHP, Ruby, Node.js, and even a Linux or Windows script. Typically these web pages generate statistics about players or games, or provide general purpose tools that players may use.

You can also use client side programming languages such as JavaScript, C/C++/C#, ASP.Net, Java, Visual Basic and even VBA macros in MS Excel to access Nu server data. These languages can load data, modify it and save it back to the Nu server. In theory you could completely build your own Nu client if you did not like the standard one.

API Detail

Calls to the server

All calls to the Nu API server ( http://api.planets.nu/ ) consist of two items:

The data can either be an object or a URL encoded string depending on which programming language and call you are using. The parameters within the data will vary depending on the API calls being made.

Normally your API call would specify a callback function to process the response from the server.

Note: The Nu API server does not currently support HTTPS.

Responses from the server

Success

If your API call is successful the Nu server will respond by returning a single item of data. This returned data is a GZIP compressed JSON string. The contents of the returned data will vary depending on the API call made.

All modern web browsers will automatically decompress this GZIPed data (including JavaScript / JQuery applications running in a browser), but other programming languages that access the data directly (Java etc) must have a GZIP decoder in place to handle this. Some have a GZIP decoder installed as standard, but some do not.

After the response arrives the next action is typically to use a JSON parser to convert the data back into an object for easy manipulation. Alternatively your application could perform various string handling operations on the JSON string to extract just the information you need.

Tip: There is a good and free JSON viewer at http://jsonviewer.stack.hu/ which may help you visualize the JSON objects that the server returns.

Failure

If the server is available, but your API call was invalid (for instance if you asked for data on a non-existing game), then you will receive an error message in the JSON string similar to the examples below:

{"success":false,"error":"Username and password are required."}
{"success":false,"error":"gameid is required"}
{"success":false,"error":"game not found."}

Note: While some responses from the API server do contain "success : true" , not all responses will. You therefore cannot safely use "success : true" as a sole method to determine whether the API call was successful. A simple alternative is to check that "success : false" is not present.

No response

If the Nu server is unavailable (for instance your internet connection is down, or the Nu server is offline / times out), then no response will be sent back from the server. You will need to provide a time-out / error function for this eventuality.

Example calls

HTTP

The server data can be accessed from and displayed directly in a web browser by using http, although this is not usually a useful way of developing an application. It is however useful for rapidly testing API calls to see what data is returned.

API calls by http needs to be encoded into a single URL string. This does not need to be in a JSON format.

Use a query ("?") after the URL to show the start of the parameters. Use an ampersand ("&") to join parameters together. Many characters must be converted into URL "percent" format. Spaces can be encoded as a "+" or as a "%20".

Returned data (in JSON format) is directly displayed in the web browser.

See http://www.w3schools.com/tags/ref_urlencode.asp for more information.

Examples:

This lists games that Joshua and Big Beefer are currently playing in.

http://api.planets.nu/games/list?username=joshua
http://api.planets.nu/games/list?username=big%20beefer

Note the %20 instead of a space in Big Beefer's name.

This lists public games that are joining or running, that are standard or team or melee games.

http://api.planets.nu/games/list?scope=0&status=1,2&type=2,3,4

Note the ampersands joining the parameters together.

JSQuery

$.ajax({
type: 'POST', //POST is preferred to GET
url: 'http://api.planets.nu/games/list',  //URL to call
dataType: 'json',
data: {username: “big beefer”}, //object or string
success: callback, //your callback function
timeout: timeout, //(optional) timeout in ms
error: errorfunction //(optional) error function
});

More info here: http://api.jquery.com/jquery.ajax/

or

$.get(
"http://api.planets.nu/games/list",  //URL to call
{username : “big beefer”}, //object  or string
callback //callback function
);

More info here: http://api.jquery.com/jquery.get/

The callback function is called when there is a response, with one parameter holding the returned data.

JavaScript

 
var myAPI = new XMLHttpRequest();
 
myAPI.onreadystatechange = function() {
if (myAPI .readyState === 4 && myAPI.status === 200)
  callback(myAPI.responseText);
}
myAPI.open("GET", “http://api.planets.nu/games/list?username=joshua”, true);
myAPI.send(null);

API calls by using the XMLHttpRequest() need to be encoded into a single URL string. This does not need to be in a JSON format.

The callback function is called when there is a response, with one parameter holding the returned data.

Python

import urllib2, httplib
import json
import StringIO
import gzip
import pickle
import csv
import datetime
 
class HandleGZippedJSON:
  def __init__(self, url):
  self.url = urllib2.quote(url.encode('utf-8','ignore'),':/?=&')
self.json_data = None
 
def run(self):
#httplib.HTTPConnection.debuglevel = 1
print self.url
request = urllib2.Request(self.url)
request.add_header('Accept-encoding', 'gzip')
opener = urllib2.build_opener()
f = opener.open(request)
c_data = f.read()
c_stream = StringIO.StringIO(c_data)
gzipper = gzip.GzipFile(fileobj=c_stream)
data = gzipper.read()
self.json_data = json.loads(data)
#return json.loads(data)
 
def main():
out = HandleGZippedJSON("http://api.planets.nu/games/list?scope=0&status=1")
out.run()
print out.json_data
 
if __name__ == '__main__':
main()

Excel / VBA

Sub DownloadFile()
Dim myURL As String
myURL = "http://api.planets.nu/game/loadturn?gameid=YYYYYY&apikey=xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.send
myURL = WinHttpReq.responseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile "C: emp\Planets.txt", 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
End Sub

JavaScript addon

If you are writing a JavaScript addon that runs with the Nu client, then another way of accessing the API is by calling the Nu client's API code rather than making the API call yourself.

nu.api.request(
/games/list //use the relative path, not the full path
{ username: “Big Beefer”},     //data is an object not a string
callback, //your callback function
timeout //(optional) timeout in ms
);

If timout is reached, then a system alert will pop up.

Table of API calls

Account management calls
Game calls
Game management calls
Information calls
Level Editor calls
Forum calls

Account management calls
/account/login Get player's API key, given login/password
/account/changeemail Change the email address for a player
/account/changepassword Change the login password for a player
/account/buyadvantage Purchase a race advantage for an Officer
/account/buyhull Purchase a starship hull for an Officer
/account/createofficer Enable a race for a player
/account/forgot Password recovery
/account/holidaymode Set or Clear Holiday Mode for a player
/account/homestats Statistics for an Officer's Homeworld
/account/loadofficer Get information for an Officer
/account/loadprofile Load a player's profile
/account/loadrecruits Load a player's recruits
/account/makepaypalpurchase Upgrade account status to Premium
/account/officers Get information on a player's Officers
/account/saveprofile Save a player's profile
/account/toggleadvantage Enable or Disable a race advantage for an Officer
/account/togglehull Enable or Disable a starship hull for an Officer
/account/updatehomeworld Update an Officer's Homeworld
/create/account Create a new player account
/player/savesettings Saves player settings.
 
Game calls
/game/deletemessage Delete an in game message
/game/loadall (Unused) Download a zip containing all turns of all players in a finished game
/game/loadevents Get public event log for a game
/game/loadinfo Get public info about a game
/game/loadscores Get public chart data (planets, military score, PBP etc) for all turns of a game
/game/loadturn Get a turn from a game (your game or finished games).
/game/nextlevel Restart your training level or move to next training level
/game/resetturn Reset your game orders back to original orders
/game/runhost Tell host to run (on private game or training level)
/game/save Save your game orders to server
/game/sendmessage Send an in-game message
/game/turnready Mark your turn as ready / not ready
/games/list Gets list of all games matching a search pattern
 
Game management calls
/account/activegames Get information on another player's currently active games
/account/addinterest Express Interest in a game
/account/createcustomgame Create a custom game
/account/creategame Create a Blitz game
/account/deletegame Delete a custom game
/account/gamelevels Get information on training levels
/account/history Get information on a player's game history
/account/hosted Get information on another player's Hosted games
/account/join Join a game
/account/mygames Get information on current player's currently active games
/account/myhosted Get information on the current player's Hosted games
/account/pauseresume Pause or Resume a Hosted game
/account/removeinterest Remove previously expressed Interest
/account/resign Resign from an ongoing game
/account/startlevel Start a training level
/account/updategame Update settings for a Hosted game
 
Information calls
/account/blitzleaders
/account/contactmessage
/account/leaderboard
/account/load
/account/loadscores
/account/notifications
/account/privateactivity
/account/privatemessage
/account/raceofficers
/account/tenacityhistory
/account/tenacityleaders
/account/topmercenaries
/account/toprecruiters
/static/all
/time Get server time and Nu year.
 
Level Editor calls
/account/createstorygame
/account/deletemap
/account/galleryimages
/account/loadmap
/account/masterplanets
/account/randmap
/account/renamestoryline
/account/savemap
/account/stories
 
Forum calls
/account/activity
/account/blogposts Get News items
/account/editpost
/account/ignoreactivity Ignore a thread or post, such that it isn't displayed
/account/ignored
/account/like
/account/listcategories
/account/loadpost
/account/post
/account/thread
/account/unignoreactivity Unignore a previously ignored thread or post

Back