Skip to content

Commit

Permalink
- Ported the types over to Python
Browse files Browse the repository at this point in the history
- Fixed a dumb url error
- Added proper return types to most API calls
  • Loading branch information
p0t4t0sandwich committed Sep 19, 2023
1 parent 969e898 commit 3944cf6
Show file tree
Hide file tree
Showing 19 changed files with 2,125 additions and 1,387 deletions.
40 changes: 27 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,13 @@ pip install requests aiohttp json

## Notes

Currently, you can only access API responses as `dict` or `list`, still trying to figure out a good way to generalize turning the JSON responses into objects (might just use class constructors as a cheap workaround).
API reponses have been mostly searialized into Python objects, but there are some issues with some of the generic types, these will need to be access like a regular dictionary.

This effects the following return types and their generic implementations:

- ActionResult
- Result
- Task

## Examples

Expand All @@ -59,9 +65,9 @@ def main():
API.Core.SendConsoleMessage("say Hello Everyone, this message was sent from the Python API!")

currentStatus = API.Core.GetStatus()
CPUUsagePercent = currentStatus["Metrics"]["CPU Usage"]["Percent"]
CPUUsagePercent = currentStatus.Metrics["CPU Usage"].Percent

print("Current CPU usage is: " + str(CPUUsagePercent) + "%")
print(f"Current CPU usage is: {CPUUsagePercent}%")

main()
```
Expand All @@ -81,9 +87,9 @@ async def main():
await API.Core.SendConsoleMessageAsync("say Hello Everyone, this message was sent from the Python API!")

currentStatus = await API.Core.GetStatusAsync()
CPUUsagePercent = currentStatus["Metrics"]["CPU Usage"]["Percent"]
CPUUsagePercent = currentStatus.Metrics["CPU Usage"].Percent

print("Current CPU usage is: " + str(CPUUsagePercent) + "%")
print(f"Current CPU usage is: {CPUUsagePercent}%")

asyncio.run(main())
```
Expand All @@ -95,6 +101,7 @@ from ampapi.modules.ADS import ADS
from ampapi.modules.Minecraft import Minecraft

API = ADS("http://localhost:8080/", "admin", "myfancypassword123")
API.Login()

# Get the available instances
instancesResult = API.ADSModule.GetInstances()
Expand All @@ -116,35 +123,36 @@ for instance in instances:
break

# Use the instance ID to get the API for the instance
Hub = API.InstanceLogin(hub_instance_id, Minecraft)
Hub = API.InstanceLogin(hub_instance_id, "Minecraft")

# Get the current CPU usage
currentStatus = Hub.Core.GetStatus()
CPUUsagePercent = currentStatus["Metrics"]["CPU Usage"]["Percent"]
CPUUsagePercent = currentStatus.Metrics["CPU Usage"].Percent

# Send a message to the console
Hub.Core.SendConsoleMessage("say Current CPU usage is: " + CPUUsagePercent + "%")
Hub.Core.SendConsoleMessage(f"say Current CPU usage is{CPUUsagePercent}%")
```

### CommonAPI Example, handling the sessionId and rememberMeToken manually (not recommended)

```python
from ampapi.ampapi import AMPAPI
from ampapi.modules.CommonAPI import CommonAPI

try:
API = AMPAPI("http://localhost:8080/")
API = CommonAPI("http://localhost:8080/")

# The third parameter is either used for 2FA logins, or if no password is specified to use a remembered token from a previous login, or a service login token.
loginResult = API.Core.Login("admin", "myfancypassword123", "", False)

if "success" in loginResult.keys() and loginResult["success"]:
if loginResult.success:
print("Login successful")
API.sessionId = loginResult["sessionID"]
API.sessionId = loginResult.sessionID
API.Core.sessionId = loginResult.sessionID

# API call parameters are simply in the same order as shown in the documentation.
API.Core.SendConsoleMessage("say Hello Everyone, this message was sent from the Python API!")
currentStatus = API.Core.GetStatus()
CPUUsagePercent = currentStatus["Metrics"]["CPU Usage"]["Percent"]
CPUUsagePercent = currentStatus.Metrics["CPU Usage"].Percent
print(f"Current CPU usage is: {CPUUsagePercent}%")

else:
Expand All @@ -155,3 +163,9 @@ except Exception as err:
# In reality, you'd handle this exception better
raise Exception(err)
```

## Release Notes - 1.3.0

- Ported the types over to Python
- Fixed a dumb url error
- Added proper return types to most API calls
29 changes: 15 additions & 14 deletions ampapi/ampapi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#!/bin/python3
# author: p0t4t0sandich
# description: A Python library for the AMP API
# An API that allows you to communicate with AMP installations from within Python
# Author: p0t4t0sandich

from __future__ import annotations
from typing import Any, TypeVar
Expand All @@ -10,6 +9,7 @@
import json

from aiohttp import ClientSession
from ampapi.types import LoginResult

class AMPAPI():
"""Class for interacting with the AMP API"""
Expand All @@ -24,7 +24,7 @@ def __init__(self, baseUri: str, username: str = "", password: str = "", remembe
# Check if the baseUri ends with a slash
if not self.baseUri[-1] == "/":
self.baseUri += "/"
self.dataSource: str = self.baseUri + "API"
self.dataSource: str = self.baseUri + "API/"

self.username: str = username
self.password: str = password
Expand Down Expand Up @@ -66,6 +66,7 @@ def api_call(self, endpoint: str, data: dict = {}) -> dict:
headers=self.headers,
data=data_json
)

res_json = json.loads(res.content)

return res_json
Expand Down Expand Up @@ -99,7 +100,7 @@ async def api_call_async(self, endpoint: str, data: dict = {}) -> dict:

return response

def Login(self) -> dict:
def Login(self) -> LoginResult:
"""
Simplified login function
:returns: dict with the result of the login
Expand All @@ -115,15 +116,15 @@ def Login(self) -> dict:
if self.rememberMeToken == "":
data["password"] = self.password

loginResult: dict = self.api_call("Core/Login", data)
loginResult: LoginResult = LoginResult(**(self.api_call("Core/Login", data)))

if "success" in loginResult.keys() and loginResult["success"] == True:
self.rememberMeToken = loginResult["rememberMeToken"]
self.sessionId = loginResult["sessionID"]
if loginResult.success == True:
self.rememberMeToken = loginResult.rememberMeToken
self.sessionId = loginResult.sessionID

return loginResult

async def LoginAsync(self) -> dict:
async def LoginAsync(self) -> LoginResult:
"""
Simplified login function
:returns: dict with the result of the login
Expand All @@ -139,10 +140,10 @@ async def LoginAsync(self) -> dict:
if self.rememberMeToken == "":
data["password"] = self.password

loginResult: dict = await self.api_call_async("Core/Login", data)
loginResult: LoginResult = LoginResult(**(self.api_call("Core/Login", data)))

if "success" in loginResult.keys() and loginResult["success"] == True:
self.rememberMeToken = loginResult["rememberMeToken"]
self.sessionId = loginResult["sessionID"]
if loginResult.success == True:
self.rememberMeToken = loginResult.rememberMeToken
self.sessionId = loginResult.sessionID

return loginResult
Loading

0 comments on commit 3944cf6

Please sign in to comment.