CREATE YOUR WORLD
Multiplay

HTTP request from the Multiplay server

15min
you can make http requests from the zepeto world multiplay server using the zepeto multiplay httpservice module integrate external web services into your business logic operations, data storage, statistical analysis, error tracking, and more please ensure that only the https protocol is used, while http is supported only in the development environment requests are allowed only on ports 80 and 443 the maximum size for request and response bodies is limited to 16kb keep the number of requests per minute below 500 to avoid potential limitations on the world service if excessive requests occur requests will fail if external web services do not respond within 5 seconds ensure that the content type in response headers matches the values defined in the httpcontenttype enum; otherwise, requests will fail given the possibility of web requests failing for various reasons, it is recommended to code defensively zepeto multiplay httpservice 📘 please refer to the following guide \[ zepeto multiplay httpservice api https //developer zepeto me/docs/multiplay server/interfaces/zepeto multiplay httpservice httpservice ] methods method description httpservice getasync(url string, headers? httpheader) promise perform http get requests asynchronously \[parameters] \ url the web address to send the request to \ headers http request headers (optional) \[return value] \ promise\<httpresponse> returns an httpresponse object containing information about the response as a promise httpservice postasync(url string, body httpbodytype, headers? httpheader) promise perform http post requests asynchronously \[parameters] \ url the web address to send the request to \ body the request body content \ headers http request headers (optional) \[return value] \ promise\<httpresponse> returns an httpresponse object containing information about the response as a promise httpservice postasync(url string, body httpbodytype, httpcontenttype httpcontenttype, headers? httpheader) promise perform http post requests asynchronously \[parameters] \ url the web address to send the request to \ body the request body content \ httpcontenttype specifies the request content type header \ headers http request headers (optional) \[return value] \ promise\<httpresponse> returns an httpresponse object containing information about the response as a promise when using this signature, if you add 'content type' to headers, it will be overwritten by what is specified in httpcontenttype other declarations declaration description httpcontenttype enumeration of constants that specify the content type for http headers \ applicationjson 'application/json' \ applicationxml 'application/xml' \ applicationurlencoded 'application/x www form urlencoded' \ textplain 'text/plain' \ textxml 'text/xml' httpbodytype type for the http request body content, which can be either a string or an object with string keys and any values httpheader type for defining http request headers, where the property values can be either strings or numbers in the object httpresponse interface that includes information about the http request result and response data \ statuscodehttp a number representing the status code of the response typically, 200 indicates a successful request \ statustexthttp a string representing the status message of the response typically, "ok" indicates a successful request \ response a string containing the http response body data 📘 http status https //developer mozilla org/en us/docs/web/http/status https //developer mozilla org/en us/docs/web/http/status code samples basic get request let's create a simple get request example using httpservice getasync when a new client connects to the multiplay room, we will send an http request to an external web service and log the result restcountries com https //restcountries com/ is an open api that provides information about various countries we will use this service to find out the capital city of japan set up multiplay, then open world multiplay/index ts and write the server script as follows 📘 please refer to the following guide \[ multiplay docid 2vrtjxdya 27bcwdacza ] import { sandbox, sandboxoptions, sandboxplayer } from "zepeto multiplay"; import { httpservice } from "zepeto multiplay httpservice"; export default class extends sandbox { oncreate(options sandboxoptions) { } onjoin(client sandboxplayer) { this findcapitalcity() } onleave(client sandboxplayer, consented? boolean) { } findcapitalcity() { // make the request to the restcountries api httpservice getasync("https //restcountries com/v3 1/name/japan?fields=capital") // handler for the http response then((httpresponse) => { // parse the json response data from the api (which is nested in http response) let countries = json parse(httpresponse response); console log("the capital city of japan is "); console log(`${countries\[0] capital}`); }); } } code description when a client connects to the multiplay room, the onjoin function is triggered, and it calls findcapitalcity if the getasync call to the restcountries api is successful, you can access the httpresponse object in the then callback parse httpresponse response to convert the api response, which is in json format, into an object by referring to the structure of the api response, you access the desired properties and then print their values when you run the multiplay server in the unity editor and play the scene, the following will be displayed in the console the capital city of japan is tokyo defensive coding practices meanwhile, as mentioned in the introductory precautions, web requests can fail for various reasons, including changes in web addresses or api response formats failure to properly handle these requests can have various adverse effects on world play, so it is recommended to code defensively, especially when dealing with http requests the following is an example of applying several defensive coding techniques to the code above findcapitalcity() { // make the request to the restcountries api httpservice getasync( "https //restcountries com/v3 1/name/japan?fields=capital", { 'accept' httpcontenttype applicationjson }) // handler for the http response then((httpresponse) => { // check if the api call returned 200(ok) or not if (httpresponse statuscode != 200) { // if it was not 200(ok), do not proceed and raise a custom error throw (`api error ${httpresponse statuscode} ${httpresponse statustext}`); } // return the json response data from the api return httpresponse response; }) // handler for the json response data from the api then((response) => { // parse the json response data let countries = json parse(response); // check if the api response data is valid if (!array isarray(countries) || !countries length) { // if it is not an array, or is empty // do not proceed and raise a custom error throw (`api error response data is not valid`); } let country = countries\[0]; // check if the 'capital' field is valid if (!country capital) { // if the 'capital' field does not exist, or is empty // do not proceed and raise a custom error throw (`api error 'capital' field not valid`); } console log("the capital city of japan is ") console log(`${country capital}`); }) // handler for errors occurring in the getasync call and 'then' clauses catch((reason) => { console log("api request error"); console log(reason); }); } the defensive coding techniques applied here include the following using the accept header the accept header is used to specify the expected content type for the response body depending on the server, the response content type can be adjusted based on the accept header checking httpresponse statuscode the httpresponse statuscode property is used to verify the success of the request validating json data structure you confirm whether the data structure of the object parsed with json parse matches the expected structure verifying property existence you ensure that the properties you intend to use actually exist in the object utilizing the promise's catch method the catch method of the promise is used to handle errors that may occur during api requests and response processing these techniques protect the code to operate reliably in the face of unexpected errors, enhancing its robustness integrating with clients via room messages http requests are only possible from the multiplay server however, by using multiplay room messages, you can trigger the server to send http requests to external web services from the client and utilize the responses within the client the following example demonstrates client server integration in this demonstration, when a button on the client's ui is pressed, the country's capital corresponding to the button is displayed 📘 please refer to the following guide \[ multiplay room message docid\ a04weva7 xyk k al0kzk ] client code import { zepetoscriptbehaviour } from 'zepeto script' import { room } from 'zepeto multiplay' import { zepetoworldmultiplay } from 'zepeto world'; import { button, text } from 'unityengine ui' export default class samplescript extends zepetoscriptbehaviour { public multiplay zepetoworldmultiplay; public room room; public countrybuttons button\[]; public capitaltext text; start() { interface response { capitals string\[] } for (const countrybutton of this countrybuttons) { countrybutton onclick addlistener(() => { if (this room !== null) { // send the country name as a 'client to server' type message to the server this room send("client to server", countrybutton getcomponentinchildren\<text>() text); } }); }; this multiplay roomcreated += (room room) => { this room = room; // handle messages received with a 'server to client' type this room addmessagehandler("server to client", (message response) => { // for countries with multiple capital cities, // join the string elements with ', ' and display on the scene this capitaltext text = message capitals join(", "); }); }; } } code description we define a listener that iterates through buttons displaying the names of countries when clicked, this listener sends a room message to the multiplay server this listener sends the country's name displayed on the button as a 'client to server' type message to handle responses, we also define a listener for processing room messages received as 'server to client' type this listener displays the capital city name received from the server on the screen if there are multiple capital cities, they are displayed on the screen, separated by commas server code import { sandbox, sandboxoptions, sandboxplayer } from "zepeto multiplay"; import { httpservice } from "zepeto multiplay httpservice"; export default class extends sandbox { oncreate(options sandboxoptions) { // handle messages received with a 'client to server' type this onmessage("client to server", (client, message) => { console log(`client ${client userid} sent request message ${message}`); this findcapitalcity(message, client); }); } onjoin(client sandboxplayer) { } onleave(client sandboxplayer, consented? boolean) { } findcapitalcity(countryname string, client sandboxplayer) { // request api with the countryname as a path parameter // the countryname is sent by the client as a room message httpservice getasync(`https //restcountries com/v3 1/name/${countryname}?fields=capital`) then((httpresponse) => { if (httpresponse statuscode != 200) { throw (`api error ${httpresponse statuscode} ${httpresponse statustext}`); } return httpresponse response; }) then((response) => { let countries = json parse(response); if (!array isarray(countries) || !countries length) { throw (`api error response data is not valid`); } let country = countries\[0]; if (!country capital) { throw (`api error 'capital' field not valid`); } // send a 'server to client' type message to the client // the message is an object containing capital city names client send("server to client", { "capitals" country capital }); }) catch((reason) => { console log("api request error"); console log(reason); }); } } code description we define a listener that, upon receiving a 'client to server' type multiplay room message, calls findcapitalcity we construct an address for the multiplay room message using the country name and make a getasync call if the getasync call is successful, the response is handled as in previous examples the capital city name obtained from the response of the restcountries api is sent to the client as a 'server to client' type room message post request lastly, let's create a post request example using httpservice postasync postman echo https //postman echo com/ is a service that provides structured responses showing what content was received from web requests, making it effective for verifying if the client has configured the request correctly through this example, we will set up a post request with query parameters, request body, and headers and ensure that the request is properly configured set up multiplay, then open world multiplay/index ts and write the server script as follows import { sandbox, sandboxoptions, sandboxplayer } from "zepeto multiplay"; import { httpcontenttype, httpservice } from "zepeto multiplay httpservice"; export default class extends sandbox { oncreate(options sandboxoptions) { } onjoin(client sandboxplayer) { this echopost() } onleave(client sandboxplayer, consented? boolean) { } echopost() { httpservice postasync( // api endpoint with a query parameter "https //postman echo com/post?argkey=argvalue", // json request body { "datakey" "datavalue" }, // request content type httpcontenttype applicationjson, // http header { "header key" "header value" }) then((httpresponse) => { if (httpresponse statuscode != 200) { throw (`api error ${httpresponse statuscode} ${httpresponse statustext}`); } return httpresponse response; }) then((response) => { let parsed = json parse(response); console log(`query parameter argkey ${parsed args argkey}`); console log(`request body datakey ${parsed data datakey}`); console log(`request header header key ${parsed headers\["header key"]}`) }) catch((reason) => { console log("api request error"); console log(reason); }); } } code description when a client connects to the multiplay room, the echopost function is called from the onjoin trigger when making the postasync request in the first parameter, we construct the url string with query parameters in the second parameter, we set the request body content in the fourth parameter, we configure the request header to specify that the request body is in json format, we set the 'application/json' content type in the third parameter if the postasync call is successful, we can access the httpresponse object in the then callback we parse httpresponse response to convert the api response in json format into an object referring to the structure of the api response, we use console output to verify whether our http request's query parameters, request body, and request header are correctly configured when you run the multiplay server in the unity editor and play the scene, the following will be displayed in the console query parameter argkey\ argvalue request body datakey\ datavalue request header header key\ header value