View Single Post
DJ Tsunami
DJ Post Spammer
Join Date: Feb 2008
Location: The Netherlands
Old 05-30-2017 , 05:11   REST in Pawn Code Examples
Reply With Quote #2

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(jsonsizeof(json));


char path[PLATFORM_MAX_PATH];
BuildPath(Path_SMpathsizeof(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(keysizeof(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 responseany 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"titlesizeof(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 responseany 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 0numTodosi++) {
        
todo view_as<JSONObject>(todos.Get(i));

        
todo.GetString("title"titlesizeof(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(todoOnTodoCreated);

    
// JSON objects and arrays must be deleted when you are done with them
    
delete todo;
}

void OnTodoCreated(HTTPResponse responseany 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(todoOnTodoUpdated);

    
delete todo;
}

void OnTodoUpdated(HTTPResponse responseany 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 responseany 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 responseany value)
{
    
char date[30];
    
response.GetHeader("Date"datesizeof(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[] bufferint maxlength)
    {
        
this.GetString("title"buffermaxlength);
    }
    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(todoOnTodoCreated);

    
delete todo;
}

void OnTodoCreated(HTTPResponse responseany 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_SMimagePathsizeof(imagePath), "data/image.jpg");

    
HTTPRequest request = new HTTPRequest("https://nghttp2.org/httpbin/image/jpeg");
    
request.DownloadFile(imagePathOnImageDownloaded);
}

void OnImageDownloaded(HTTPStatus statusany 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_SMimagePathsizeof(imagePath), "data/image.jpg");

    
HTTPRequest request = new HTTPRequest("https://example.com/upload");
    
request.UploadFile(imagePathOnImageUploaded);
}

void OnImageUploaded(HTTPStatus statusany 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 responseany value)
{
    if (
response.Status != HTTPStatus_OK) {
        
// Failed to post form
        
return;
    }

    
// The JSON response data can be retrieved here

__________________
Advertisements | REST in Pawn - HTTP client for JSON REST APIs
Please do not PM me with questions. Post in the plugin thread.

Last edited by DJ Tsunami; 06-05-2021 at 13:52.
DJ Tsunami is offline