To create a simple command line app that uses the ServiceNow REST API:
- Create a .NET Core 10.0 Console project in Visual Studio
- Ensure that you have specified <LangVersion>latest</LangVersion> in the csproj file, e.g.:
<ProjectSdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<AnalysisMode>Recommended</AnalysisMode>
<AnalysisLevel>latest-recommended</AnalysisLevel>
</PropertyGroup>
<ItemGroup>
<FolderInclude="Properties\" />
</ItemGroup>
<ItemGroup>
<PackageReferenceInclude="Newtonsoft.Json"Version="13.0.1" />
<PackageReferenceInclude="ServiceNow.Api"Version="1.2.*" />
</ItemGroup>
</Project>
- Edit Program.cs to be similar to the following:
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingSystem.Runtime.Serialization;namespaceServiceNow.Api.Example;publicstaticclassProgram{publicasyncstaticTaskMain(string[]args){varaccount=args[0];varusername=args[1];varpassword=args[2];Console.WriteLine("Lists Windows Servers");usingvarserviceNowClient=newServiceNowClient(account,username,password,newOptions());// MANDATORY: The table name can be obtained from this list:// https://docs.servicenow.com/bundle/london-platform-administration/page/administer/reference-pages/reference/r_TablesAndClasses.htmlconststringtableName="cmdb_ci_win_server";// OPTIONAL: The main sysparm_query goes here. See documentation here:// https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/integrate/inbound_rest/reference/r_TableAPI-GET.html// If you omit this, an unfiltered result will be returnedconststringquery="name";// OPTIONAL: The fields to bring back.// This should be set to constrain the response to ONLY the fields that you are going to process.// Doing so will hugely speed up your query.varfields=newList<string>{"sys_id","name"};varjObjectResults=awaitserviceNowClient.GetAllByQueryAsync(tableName,query,fields).ConfigureAwait(false);varmodelResults=jObjectResults.ConvertAll(o =>o.ToObject<WinServerModel>());Console.WriteLine("Windows Servers:");foreach(varmodelResultinmodelResults){Console.WriteLine($" - {modelResult.Id}: {modelResult.Name}");}}}[DataContract]publicclassWinServerModel{[DataMember(Name="sys_id")]publicstringId{get;set;}[DataMember(Name="name")]publicstringName{get;set;}}