How to call REST Web Service in unity3d
In this tutorial, I will explain how to call REST Web Service in unity3d. First let’s create a simple REST web Service using ASP.NET Web API then we will call it in unity3d. We will test the application for GET and POST requests.
IDE/Engine used for this project: Visual studio 2017 community edition, unity 2017.1 Personal Edition
Create a REST Web Service using ASP.NET Web API
We will create a simple REST web service which will GET and POST values from a sample text file.
- Create a new project in visual studio. Select Web template and create ASP.NET Web Application project.
- Select Web API template and click on OK button. This will create the project with ASP.NET Web API template.
- Add a class in Models folder. Let’s name the class as Test. The body of the class is given below.
12345678910using System;namespace SampleRestService.Models{public class Test{public int Id;public string Name;}} - Open Values controller under Controller folder. Edit the class as below given code. This will be the functionality of our GET and POST service.
12345678910111213141516171819202122232425262728293031using System.Web.Http;using System.IO;using SampleRestService.Models;using System;namespace SampleRestService.Controllers{public class ValuesController : ApiController{// GET api/values/5public string Get(int id){string[] lines = File.ReadAllLines("D:/test.txt");foreach(string line in lines){if (line.Contains(id.ToString())){return line;}}return "No Entry for this ID";}// POST api/valuespublic void Post([FromBody] Test value){File.AppendAllText("D:/test.txt", Environment.NewLine + Newtonsoft.Json.JsonConvert.SerializeObject(value));}}} - Run the application. It will open a web page in the browser. Click on the API link on the top. It will open the page with REST API details. Our service setup is now complete.
Call Rest Web Service in unity3d
Now we will see how to call REST Web Service in unity3d. We can either use WWW class or UnityWebRequest class to GET and POST the data from the REST Web Service. First, we will post some value then we will retrieve them using GET method.
POST Request
Create the below given script and attach it to the Main Camera or any other GameObject.
Using WWW class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.Networking; using System.Text; using System; public class CallRestService : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(postWWW()); } IEnumerator postWWW() { ///<summary> /// Post using WWW class /// </summary> Dictionary<string,string> headers = new Dictionary<string, string> (); headers.Add ("Content-Type", "application/json"); var jsonString = "{\"Id\":2,\"Name\":\"Mary\"}"; byte[] byteData = System.Text.Encoding.ASCII.GetBytes(jsonString.ToCharArray()); WWW wwwPostRequest = new WWW ("http://localhost:55376/api/values", byteData, headers); yield return wwwPostRequest; if (string.IsNullOrEmpty (wwwPostRequest.error)) { Debug.Log ("Form upload complete!"); } else { Debug.Log (wwwPostRequest.error); } } } |
Result: Form upload complete message will print in unity console.
The sample text file will be updated after this POST request.
Using UnityWebRequest class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.Networking; using System.Text; using System; public class CallRestService : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(postUnityWebRequest()); } IEnumerator postUnityWebRequest() { ///<summary> /// Post using UnityWebRequest class /// </summary> var jsonString = "{\"Id\":3,\"Name\":\"Roy\"}"; byte[] byteData = System.Text.Encoding.ASCII.GetBytes(jsonString.ToCharArray()); UnityWebRequest unityWebRequest = new UnityWebRequest ("http://localhost:55376/api/values", "POST"); unityWebRequest.uploadHandler = new UploadHandlerRaw (byteData); unityWebRequest.SetRequestHeader ("Content-Type", "application/json"); yield return unityWebRequest.Send(); if(unityWebRequest.isNetworkError || unityWebRequest.isHttpError) { Debug.Log(unityWebRequest.error); } else { Debug.Log("Form upload complete! Status Code: " + unityWebRequest.responseCode); } } } |
If you want to get response message after POST request from the server, then add DownloadHandler also with the unity web request.
1 2 |
DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer(); unityWebRequest.downloadHandler = downloadHandlerBuffer; |
After completing POST request, you can access the response as given below.
1 |
string response = unityWebRequest.downloadHandler.text; |
Result: Form upload complete message with response code will print in unity console.
The sample text file will be updated after this POST request.
GET Request
Create the below given script and attach it to the Main Camera or any other GameObject for implementing GET request.
Using WWW class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.Networking; using System.Text; using System; public class CallRestService : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(getWWW()); } IEnumerator getWWW() { // First define the url, this should be a valid url string url = "http://localhost:55376/api/values/2"; WWW www = new WWW(url); while (!www.isDone) yield return null; if (string.IsNullOrEmpty (www.error)) { Debug.Log (www.text); } else Debug.Log (www.error); } } |
Result:
Using UnityWebRequest class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.Networking; using System.Text; using System; public class CallRestService : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(getUnityWebRequest()); } IEnumerator getUnityWebRequest() { UnityWebRequest www = UnityWebRequest.Get ("http://localhost:55376/api/values/3"); yield return www.Send(); if(www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { Debug.Log (www.downloadHandler.text); } } } |
Result:
Hope, You get an idea about how to call REST Web Service in unity3d. Please post your comments for queries and feedback.
Latest posts by Gyanendu Shekhar (see all)
- Create fake shadow using blob shadow projector: Unity tutorial - October 2, 2018
- Using Reflection Probe: Unity Tutorial - October 1, 2018
- Difference Between Material and Shared Material: Unity Tutorial - September 23, 2018
How to call https certificates by bypassing ssl policy errors and certificates
Hi, Thanks for the article. I’m trying to call an api as told by you but it’s giving me error – “Cannot connect to destination host”. I’ve provided correct url as when I enter that url in browser, it gives me result. But it’s not getting hit from my app.
Please provide some help. Thanks.
Hi Shailesh,
Did you test your service first with some client side app like Postman. If It is working in Postman, then it should also work in unity as given in the tutorial. Check your url using debug.log and make sure it is correct. If the service is hosted on cloud then try without proxy network.
Thank you much Gyanendu… Was trying to use .net WebRequest which was locking up unity. UnityWebRequest solved the problem. I’m using this to interact with a raspberry pi express api to toggle pins. Works great.
UnityWebRequest unityWebRequest =
UnityWebRequest.Get(“http://208…./toggle/27”);
unityWebRequest.SendWebRequest();
unityWebRequest.Dispose();
Hi,
Thanks for this tutorial, test.txt file not update ,Null display.