This topic is locked

Using RestSharp to make an API insert call

12/2/2023 7:38:43 AM
ASPRunner.NET General questions
D
david powell author

Hi,
I am following the user guide to do an api call to insert a record:

C# code (using RestCharp):

var client = new RestClient("http://localhost:8086/api/v1?table=categories&action=insert");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AlwaysMultipartFormData = true;
request.AddParameter("CategoryName", "Beer");
request.AddParameter("Description", "Beer and stuff");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

I have added this line to my c# imports ( I believe the library is actually called RestSharp rather than RestCharp)

// Add 'using' directives here for all your event handlers.
// For example:
// using System.Security.Cryptography;
using RestSharp;

but getting this error message on building:

include\tasklist_TableEvents.cs(16,7): error CS0246: The type or namespace name 'RestSharp' could not be found (are you missing a using directive or an assembly reference?) [C:\projects_v3\emailsendv112\output\emailsendv112.csproj]
include\CommonEvents.cs(16,7): error CS0246: The type or namespace name 'RestSharp' could not be found (are you missing a using directive or an assembly reference?) [C:\projects_v3\emailsendv112\output\emailsendv112.csproj]

(same error with using RestCharp
include\tasklist_TableEvents.cs(16,7): error CS0246: The type or namespace name 'RestCharp' could not be found (are you missing a using directive or an assembly reference?) [C:\projects_v3\emailsendv112\output\emailsendv112.csproj]
include\CommonEvents.cs(16,7): error CS0246: The type or namespace name 'RestCharp' could not be found (are you missing a using directive or an assembly reference?) [C:\projects_v3\emailsendv112\output\emailsendv112.csproj]

I am sure I am missing some very simple step - can anyone share with me what it might be ?!

Many thanks
David.

Sergey Kornilov 12/2/2023

Imports event is for adding "using" directives of libraries that are a part of core .NET package. If you need to use a third party DLL in your project check a link at the end of this article:
https://xlinesoft.com/asprunnernet/docs/c-imports.htm

D
david powell author 12/3/2023

Thanks Admin!

I have added the RestSharp.dll ( and also NewtonSoftJson.dll and System.Net.Http which it also needs) to custom/bin/ directory.

I have placed the following lines in the custom c# file
using RestSharp;
using System.Net.Http;
using Newtonsoft.Json;

And am almost there, but on building getting the following error messages

Classes\XVar.cs(172,13): error CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'. [C:\projects_v3\emailsendv112\output\emailsendv112.csproj]
include\tasklist_TableEvents.cs(43,1): error CS0012: The type 'System.IDisposable' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. [C:\projects_v3\emailsendv112\output\emailsendv112.csproj]

... and some others of the same nature. I cannot find any documentation as to adding references to assemblies in asprunner... where do I do that? I am building with visual studio 2019 and framework 4.8.

Many thanks....

D
david powell author 12/3/2023
F
FR 2/2/2024

Did this ever get resolved? I will be needing to do this as well.

Sergey Kornilov 2/2/2024

In our tests it works right out of the box.

D
david powell author 2/4/2024

Yes, I did get it to work, but using Newtonsoft and not RestSharp

  1. Right or wrong make c# directory ( at bottom of events tab) look like this:

using System;
using System.IO;
using System.Web;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

using System.Collections.Generic;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

  1. .In 'styles' tab, scroll to the very bottom and under 'custom files' create a directory called 'bin' if one doesnt exist already.
    .....right click bin and import Newtonsoft.json.dll (which you can google to find a copy of).


  2. I have edited this block of code, so it is now more complete - it performs a api get request, retrieves a json, parses it, does some processing and then does a confirmatory api post to confirm safe receipt for example. I have removed the code concerning processing, so just the structure remains.



Bottom line is it does compile and work, and perhaps might be useful as a basis for you.

string baseUrl = "https://xxxx.co.uk/api/v1/customers/test1";
// Constructing URL parameters
var uriBuilder = new UriBuilder(baseUrl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
// Add parameters
query["q1"] = datalocationlist["q1"];
query["createdFrom"] = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
query["limit"] = "100";
query["offset"] = "0";
// Set the updated query string
uriBuilder.Query = query.ToString();
// Final URL
url = uriBuilder.ToString();
myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.Headers["Authorization"] = "Basic xxxxxx";
myReq.Accept = "/";
myReq.UserAgent = "YourAppName/1.0";

try {
using(WebResponse wr = myReq.GetResponse()) using(
Stream responseStream =
wr.GetResponseStream()) using(StreamReader reader =
new StreamReader(responseStream)) {
// Read the response content
string responseContent = reader.ReadToEnd();

// Parse JSON
JObject jsonResponse = JObject.Parse(responseContent);

// Get the "data" array
JArray itemsArray = (JArray)jsonResponse["data"];

foreach (JToken item in itemsArray) {
// Extract values from the item
string fn = item.Value<string>("firstName");
string ln = item.Value<string>("lastName");
// Extract values from the "address" sub-array
JObject addressObject = (JObject)item["address"];
string sa = addressObject.Value<string>("streetAddress");
string hn = addressObject.Value<string>("houseNumber");
// do some processing

////////send a post response
url = "https://test.om/api/v1/customers/test/Results";
string authorizationHeader = "Basic xxxxxxxx";

string jsonBody = "[" + "{" + "\"outcome\": 1," + "\"Id\": \"" +
Id.ToString() + "\"," + "\"siteid\": \"" +
datachec["siteid"].ToString() + "\"" + "}" + "]";
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "*/*"; // Set the Accept property

request.Headers.Add("Authorization", authorizationHeader);
request.ContentType = "application/json";
request.UserAgent = "Pharmace"; // Set your desired User-Agent

using(var streamWriter = new StreamWriter(request.GetRequestStream())) {
streamWriter.Write(jsonBody);
streamWriter.Flush();
streamWriter.Close();
}

try {
using(WebResponse rresponse = request.GetResponse()) using(
Stream rresponseStream =
rresponse
.GetResponseStream()) using(StreamReader rstreamReader =
new StreamReader(
rresponseStream)) {
string rresponseContent = rstreamReader.ReadToEnd();
// process reslt
}
} catch (WebException ex) {
// Handle exceptions or display error messages
string exceptionDetails =
"Exception: " + ex.Message + "\nStackTrace: " + ex.StackTrace;
}

// end send confirmation api and insert into tasklist process
////
}

}
catch (WebException ex) {
// Handle exceptions, e.g., network errors
HttpWebResponse httpResponse = ex.Response as HttpWebResponse;
if (httpResponse != null) {
}
}