Code Examples
JSON
Create a JSON object
PHP Code:
JSONObject someObject = new JSONObject();
someObject.SetBool("someBool", false);
someObject.SetFloat("someFloat", 1.0);
someObject.SetInt("someInt", 2);
someObject.SetString("someString", "three");
someObject.SetNull("someNull");
delete someObject;
Create a JSON array
PHP Code:
JSONArray someArray = new JSONArray();
someArray.PushBool(false);
someArray.PushFloat(1.0);
someArray.PushInt(2);
someArray.PushString("three");
someArray.PushNull();
delete someArray;
You can use the Set*() methods if you need to replace values at a specific index in the array.
Nest JSON
PHP Code:
someObject.Set("someArray", someArray);
JSONArray someArrayCopy = view_as<JSONArray>(someObject.Get("someArray"));
delete someArrayCopy;
Export to and import from files and strings
PHP Code:
char json[1024];
someObject.ToString(json, sizeof(json));
char path[PLATFORM_MAX_PATH];
BuildPath(Path_SM, path, sizeof(path), "data/array.json");
JSONArray someArray = JSONArray.FromFile(path);
See the encoding flags at the top of json.inc if you want to format the output.
Iterate over the keys in a JSON object
PHP Code:
JSONObjectKeys keys = someObject.Keys();
char key[64];
while (keys.ReadKey(key, sizeof(key))) {
PrintToServer("%s", key);
}
delete keys;
HTTP
Retrieve an item
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
HTTPRequest request = new HTTPRequest("https://jsonplaceholder.typicode.com/todos/1");
request.Get(OnTodoReceived);
}
void OnTodoReceived(HTTPResponse response, any value)
{
if (response.Status != HTTPStatus_OK) {
// Failed to retrieve todo
return;
}
// Indicate that the response contains a JSON object
JSONObject todo = view_as<JSONObject>(response.Data);
char title[256];
todo.GetString("title", title, sizeof(title));
PrintToServer("Retrieved todo with title '%s'", title);
}
Retrieve a collection
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
HTTPRequest request = new HTTPRequest("https://jsonplaceholder.typicode.com/todos");
request.Get(OnTodosReceived);
}
void OnTodosReceived(HTTPResponse response, any value)
{
if (response.Status != HTTPStatus_OK) {
// Failed to retrieve todos
return;
}
// Indicate that the response contains a JSON array
JSONArray todos = view_as<JSONArray>(response.Data);
int numTodos = todos.Length;
JSONObject todo;
char title[256];
for (int i = 0; i < numTodos; i++) {
todo = view_as<JSONObject>(todos.Get(i));
todo.GetString("title", title, sizeof(title));
PrintToServer("Retrieved todo with title '%s'", title);
// Get() creates a new handle, so delete it when you are done with it
delete todo;
}
}
Create an item
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
JSONObject todo = new JSONObject();
todo.SetBool("completed", false);
todo.SetInt("userId", 1);
todo.SetString("title", "foo");
HTTPRequest request = new HTTPRequest("https://jsonplaceholder.typicode.com/todos");
request.Post(todo, OnTodoCreated);
// JSON objects and arrays must be deleted when you are done with them
delete todo;
}
void OnTodoCreated(HTTPResponse response, any value)
{
if (response.Status != HTTPStatus_Created) {
// Failed to create todo
return;
}
JSONObject todo = view_as<JSONObject>(response.Data);
PrintToServer("Created todo with ID %d", todo.GetInt("id"));
}
Update an item
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
JSONObject todo = new JSONObject();
todo.SetBool("completed", true);
HTTPRequest request = new HTTPRequest("https://jsonplaceholder.typicode.com/todos/1");
// Some APIs replace the entire object when using Put,
// in which case you need to use Patch instead.
httpClient.Put(todo, OnTodoUpdated);
delete todo;
}
void OnTodoUpdated(HTTPResponse response, any value)
{
if (response.Status != HTTPStatus_OK) {
// Failed to update todo
return;
}
JSONObject todo = view_as<JSONObject>(response.Data);
PrintToServer("Updated todo with ID %d", todo.GetInt("id"));
}
Delete an item
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
HTTPRequest request = new HTTPRequest("https://jsonplaceholder.typicode.com/todos/1");
request.Delete(OnTodoDeleted);
}
void OnTodoDeleted(HTTPResponse response, any value)
{
if (response.Status != HTTPStatus_OK) {
// Failed to delete todo
return;
}
PrintToServer("Deleted todo");
}
Append query parameters to the URL
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
HTTPRequest request = new HTTPRequest("https://jsonplaceholder.typicode.com/todos");
request.AppendQueryParam("userId", "%d", 1);
}
The parameter name and value are automatically URL encoded.
Set the credentials for HTTP Basic authentication
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
HTTPRequest request = new HTTPRequest("https://nghttp2.org/httpbin/basic-auth/username/password");
request.SetBasicAuth("username", "password");
}
Set request headers
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
HTTPRequest request = new HTTPRequest("https://nghttp2.org/httpbin/bearer");
request.SetHeader("Authorization", "Bearer %s", "some-token");
}
Get response headers
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
HTTPRequest request = new HTTPRequest("https://nghttp2.org/httpbin/get");
request.Get(OnTodosReceived);
}
void OnTodosReceived(HTTPResponse response, any value)
{
char date[30];
response.GetHeader("Date", date, sizeof(date));
PrintToServer("Date: %s", date);
}
Resource methodmaps
You can also write your own methodmaps which inherit from JSONObject, and which abstract away the fields of a resource. This makes your code cleaner when reading and writing resources.
plugin.inc
PHP Code:
methodmap Todo < JSONObject
{
// Constructor
public Todo() { return view_as<Todo>(new JSONObject()); }
public void GetTitle(char[] buffer, int maxlength)
{
this.GetString("title", buffer, maxlength);
}
public void SetTitle(const char[] value)
{
this.SetString("title", value);
}
property bool Completed {
public get() { return this.GetBool("completed"); }
public set(bool value) { this.SetBool("completed", value); }
}
property int Id {
public get() { return this.GetInt("id"); }
}
property int UserId {
public get() { return this.GetInt("userId"); }
public set(int value) { this.SetInt("userId", value); }
}
};
plugin.sp
PHP Code:
#include <sourcemod>
#include <ripext>
#include <plugin>
public void OnPluginStart()
{
Todo todo = new Todo();
todo.Completed = false;
todo.UserId = 1;
todo.SetTitle("foo");
HTTPRequest request = new HTTPRequest("https://jsonplaceholder.typicode.com/todos");
request.Post(todo, OnTodoCreated);
delete todo;
}
void OnTodoCreated(HTTPResponse response, any value)
{
if (response.Status != HTTPStatus_Created) {
// Failed to create todo
return;
}
Todo todo = view_as<Todo>(response.Data);
PrintToServer("Todo created with ID %d", todo.Id);
}
Files
Download a file
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
char imagePath[PLATFORM_MAX_PATH];
BuildPath(Path_SM, imagePath, sizeof(imagePath), "data/image.jpg");
HTTPRequest request = new HTTPRequest("https://nghttp2.org/httpbin/image/jpeg");
request.DownloadFile(imagePath, OnImageDownloaded);
}
void OnImageDownloaded(HTTPStatus status, any value)
{
if (status != HTTPStatus_OK) {
// Download failed
return;
}
PrintToServer("Download complete");
}
Upload a file
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
char imagePath[PLATFORM_MAX_PATH];
BuildPath(Path_SM, imagePath, sizeof(imagePath), "data/image.jpg");
HTTPRequest request = new HTTPRequest("https://example.com/upload");
request.UploadFile(imagePath, OnImageUploaded);
}
void OnImageUploaded(HTTPStatus status, any value)
{
if (status != HTTPStatus_OK) {
// Upload failed
return;
}
PrintToServer("Upload complete");
}
Forms
Post form data
PHP Code:
#include <sourcemod>
#include <ripext>
public void OnPluginStart()
{
HTTPRequest request = new HTTPRequest("https://nghttp2.org/httpbin/post");
request.AppendFormParam("title", "%s", "foo");
request.PostForm(OnFormPosted);
}
void OnFormPosted(HTTPResponse response, any value)
{
if (response.Status != HTTPStatus_OK) {
// Failed to post form
return;
}
// The JSON response data can be retrieved here
}
__________________