Code structure - tsukinoko-kun/papermc-web-api GitHub Wiki
Web API
io.frankmayer.papermcwebapi.handler.HttpHandlerWrapper
implements com.sun.net.httpserver.HttpHandler
Create a child class of HttpHandlerWrapper
in io.frankmayer.papermcwebapi.handler
to register it as an HTTP endpoint.
The path of the endpoint is provided with the getRoute
method.
Keep in mind to only use valid URL characters for the route.
get
protected Object get(final HttpExchange t, final OfflinePlayer authorized) throws Exception
The get
method is to handle the HTTP requests.
Return any String
, byte[]
, Number
, Boolean
, Iterable
or Object
you want as the response body.
You can set the Content-Type
response header manually.
If not provided, the server will set the Content-Type
to text/plain
for String
and Number
.
And to application/json
for Iterable
and Object
.
The first parameter final HttpExchange t
comes from the web server and contains everything you need from request and response.
The second parameter final OfflinePlayer authorized
contains the OfflinePlayer
if the requestor is logged in and not on the Minecraft server.
If the requestor is online on the Minecraft server,
you can cast this to a Player
.
If the requestor is not logged in, this parameter is null
.
Status codes
Throw an Exception to return an error status code.
Exception | Status code |
---|---|
java.lang.IllegalArgumentException |
400 |
io.frankmayer.papermcwebapi.exceptions.UnauthorizedException |
401 |
java.lang.Exception |
500 |
If you set a Location
response header, the status code is automatically set to 302
.
Example
package io.frankmayer.papermcwebapi.handler;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.sun.net.httpserver.HttpExchange;
import io.frankmayer.papermcwebapi.Main;
import io.frankmayer.papermcwebapi.exceptions.UnauthorizedException;
public class ExampleHandler extends HttpHandlerWrapper {
@Override
public String getRoute() {
return "example";
}
@Override
protected Object get(final HttpExchange t, final OfflinePlayer authorized) throws Exception {
if (authorized == null) {
// Unauthorized
throw new UnauthorizedException("You have to be authorized to access this resource.");
}
// Authorized
final var msg = String.format("Hello %s!", player.getName());
if (authorized instanceof final Player player) {
// Authorized and online
player.sendMessage(msg);
}
return msg;
}
}
Lua
Create a child class of LuaValue
in io.frankmayer.papermcwebapi.lua
. All classes in this package that extend LuaValue
will be added to the Lua Paper
global table.
Gson
io.frankmayer.papermcwebapi.gson.GsonEnhancement<T extends Object>
extends com.google.gson.TypeAdapter<T>
Class for simplifying the extensibility of Gson.
Create child classes of GsonEnhancement
in io.frankmayer.papermcwebapi.gson
,
the class will then be automatically registered as a TypeAdapter
for Gson.