The API enables logged in users to more easily query ladder data.

Currently the API exposes data as it is structured within the database.

The API uses the Django Rest Framework: <https://www.django-rest-framework.org/>

## Usage

You need to be logged in to view the API via the website. If you are, endpoints are listed here: <https://aiarena.net/api/>  
To get an API token go [here](https://aiarena.net/profile/token/).

### List data objects - 
Get a list of matches: <https://aiarena.net/api/matches/>

### Get specific item
Get match ID 4567: <https://aiarena.net/api/matches/4567>

### Filter
Get all active users: <https://aiarena.net/api/users/?is_active=true>

### Search
Search for users with "lad" in one of their fields: <https://aiarena.net/api/users?search=lad>

### Order
Get most recent results first: <https://aiarena.net/api/results?ordering=-created>

## Example scenarios:

### Download all of a bot's replays:

1. Obtain the bot's id from <https://aiarena.net/api/bots/>  
2. Get a list of all the bot's participations in matches: https://aiarena.net/api/match-participations/?bot=BOT_ID_HERE  
3. For each match id in the participants list:  
&nbsp;&nbsp;&nbsp;&nbsp;Get the result for that match: https://aiarena.net/api/results/?match=MATCH_ID_HERE  
&nbsp;&nbsp;&nbsp;&nbsp;Download the replay using the URL in the replay_file field

### Use Python to download the bot's latest 100 replays
1. Obtain your API Token [here](https://aiarena.net/profile/token/)
2. Follow the above steps to get the bot's id
3. Execute the following (after inputting necessary values):
import json
import os

import requests

# Download
bot_id = 0  # insert bot id
token = ''  # insert token you received from admin
file_path = './replays/'  # insert file path
auth = {'Authorization': f'Token {token}'}

# requests.get(url).text returns a dictionary formatted as a string and we need dictionaries
response = requests.get(f'https://aiarena.net/api/match-participations/?bot={bot_id}', headers=auth)
assert response.status_code == 200, 'Unexpected status_code returned from match-participations'
participation = json.loads(response.text)
for i in range(len(participation['results'])):
    print(f'Downloading match {participation["results"][i]["match"]}')
    response = requests.get(f'https://aiarena.net/api/results/?match={participation["results"][i]["match"]}', headers=auth)
    assert response.status_code == 200, 'Unexpected status_code returned from results'
    match_details = json.loads(response.text)
    replay_file = match_details['results'][0]['replay_file']
    if replay_file not in (None, 'null'):
        replay = requests.get(replay_file, headers=auth)
        with open(os.path.join(file_path, str(participation["results"][i]["match"])+'.SC2Replay'), 'wb') as f:

### Get the top 10 active bots ranked by ELO
Order by `elo` descending, and limit the page to 10 entries: