Make HTTP Requests to the Web API from .NET Applications
- 7 minutes to read
You can send requests to a Web API service from any .NET application with the HttpClient library. Use the OData syntax to build requests. See the following topics for more information on OData query options:
The examples below send requests to the Web API service available at the following address: https://localhost:44319/
.
Get a JWT Authentication Token
To obtain the JWT Authentication token for further data requests, send a request to the following endpoint: api/Authentication/Authenticate
. The following example uses “Sam” as a user name and an empty password:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ConsoleApp1 {
class Program {
static async Task Main(string[] args) {
HttpClient httpClient = new HttpClient();
// Obtain a JWT token.
StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);
// Save the token for further requests.
var token = await response.Content.ReadAsStringAsync();
// Set the authentication header.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
}
}
Get Business Objects
The following code retrieves the LastName and Email fields of the Employee business object where FirstName equals “Mary”:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ConsoleApp1 {
class Program {
static async Task Main(string[] args) {
HttpClient httpClient = new HttpClient();
// Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);
// Save the token for further requests.
var token = await response.Content.ReadAsStringAsync();
// Set the authentication header.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
// Send a request to fetch data.
string requestAddress = "https://localhost:44319/api/odata/Employee";
var employees = await httpClient.GetStringAsync($"{requestAddress}?$filter=FirstName eq 'Mary'&$select=LastName,Email");
Console.WriteLine(employees);
}
}
}
Result:
{"@odata.context":"https://localhost:44319/api/odata/$metadata#Employee(LastName,Email)",
"value":[{"LastName":"Tellitson",
"Email":"Mary_Tellitson@example.com"}]}
Get Related Business Objects
Use the $expand OData query parameter to obtain related business objects. The example below uses $expand to get the related Department object in addition to data retrieved in the example above.
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 {
class Program {
static async Task Main(string[] args) {
HttpClient httpClient = new HttpClient();
// Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);
// Save the token for further requests.
var token = await response.Content.ReadAsStringAsync();
// Set the authentication header.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
// Send a request to fetch data.
string requestAddress = "https://localhost:44319/api/odata/Employee";
var employees = await httpClient.GetStringAsync($"{requestAddress}?$filter=FirstName eq 'Mary'&$select=LastName,Email&$expand=Department");
Console.WriteLine(employees);
}
}
}
Result:
{"@odata.context":"https://localhost:44319/api/odata/$metadata#Employee(LastName,Email,Department())",
"value":[{"LastName":"Tellitson",
"Email":"Mary_Tellitson@example.com",
"Department":{
"Oid":"6eff292f-f871-4237-a22c-8a50aa747ea3",
"Title":"Development Department",
"Description":"The Information Technology Department manages the company's information infrastructure and online assets.",
"Location":"Building 2",
"Office":"205"}
}]
}
The $expand parameter also allows you to obtain a collection of related objects. The following example gets LastName, Email, and the related Tasks collection of the Employee business object where FirstName equals “Mary”:
//...
string requestAddress = "https://localhost:44319/api/odata/Employee";
var employees = await httpClient.GetStringAsync($"{requestAddress}?$filter=FirstName eq 'Mary'&$select=LastName,Email&$expand=Tasks");
// ...
Result:
{"@odata.context":"https://localhost:44319/api/odata/$metadata#Employee(LastName,Email,Tasks())",
"value":[{"LastName":"Tellitson",
"Email":"Mary_Tellitson@example.com",
"Tasks":[{"Oid":"b958f20a-118d-4af0-b249-94445608549d",
"Subject":"2022 Brochure Designs",
"DueDate":"2022-01-15T00:00:00+04:00",
"StartDate":"0001-01-01T00:00:00Z",
"Status":"Deferred",
"PercentCompleted":0,
"Priority":"Normal"},
{"Oid":"7de87fc8-4dc0-4b76-82b3-18dffdc61ba4",
"Subject":"Review Benefits",
"DueDate":"2021-10-02T00:00:00+04:00",
"StartDate":"2021-09-12T00:00:00+04:00",
"Status":"Completed",
"PercentCompleted":100,
"Priority":"Normal"},
{"Oid":"67d36cda-a261-489f-afa9-c8ac43e1c2ea",
"Subject":"Lunch Potluck",
"DueDate":"2021-10-03T00:00:00+04:00",
"StartDate":"0001-01-01T00:00:00Z",
"Status":"Deferred",
"PercentCompleted":0,
"Priority":"Low"}
]
}]
}
The $expand parameter can be applied to more than one level of related business objects. The following example retrieves a data chain that consists of two related business objects:
// ...
string requestAddress = "https://localhost:44319/api/odata/Department";
var departments = await httpClient.GetStringAsync($"{requestAddress}?$select=Title&$expand=Employees($select=FirstName,LastName;$expand=Tasks($select=Subject))");
// ...
Result:
{"@odata.context": "https://localhost:44319/api/odata/$metadata#Department(Title,Employees(FirstName,LastName,Tasks(Subject)))",
"value": [{ "Title": "Human Resources",
"Employees": [{ "FirstName": "Angela",
"LastName": "Gross",
"Tasks": [{ "Subject": "Create 2022 R&D Plans"},
{ "Subject": "Submit D&B Number to ISP for Credit Approval"},
{ "Subject": "Deliver R&D Plans for 2022"}]
},
{ "FirstName": "Barbara",
"LastName": "Faircloth",
"Tasks": [{ "Subject": "Subject": "Deliver R&D Plans for 2022"},
{ "Subject": "Submit D&B Number to ISP for Credit Approval"},
{ "Subject": "Create 2022 R&D Plans"}]
}]
},
{ "Title": "Purchasing",
"Employees": [{ "FirstName": "Ernest",
"LastName": "Webb",
"Tasks": [{ "Subject": "Submit D&B Number to ISP for Credit Approval"},
{ "Subject": "Deliver R&D Plans for 2022"}]
},
...
]
}]
}
The default max expansion depth equals two. You can change this parameter as described in the following topic: Change the Expansion Depth for Related Business Objects.
Create a Business Object
The code below adds a new Employee instance with the FirstName field set to “Mary” and the LastName field set to “Gordon”:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 {
class Program {
static async Task Main(string[] args) {
HttpClient httpClient = new HttpClient();
// Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);
// Save the token for further requests.
var token = await response.Content.ReadAsStringAsync();
// Set the authentication header.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
// Pass data to the Web API service.
StringContent dataHttpContent = new StringContent(@"{ ""FirstName"": ""Mary"", ""LastName"":""Gordon"" }", Encoding.UTF8, "application/json");
var dataResponse = await httpClient.PostAsync($"{requestAddress}", dataHttpContent);
Console.WriteLine(dataResponse.StatusCode);
}
}
}
Result (the dataResponse.StatusCode value): Created