Web Services And Web
API
WEB Service asp.net
• A web service is a web-based functionality accessed using the HTTP
protocols of the web to be used by the web applications.
• By using Web services, your application can publish its function to the
rest of the world
• Web services can be used by other applications (e.g Web services your
accounting department's Windows servers can connect with your IT
supplier's UNIX server).
How to create an Asp.Net core web API?
Visual Studio 2022
you need to Enable CORS (Cross Origin Resource Sharing)
var builder = WebApplication.CreateBuilder(args);
To allow remote client communication
// Add services to the container. Add all red code to the Program file
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(o =>
{
o.AddPolicy("_myAllowSpecificOrigins", p =>
p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.UseCors("_myAllowSpecificOrigins");
app.UseHttpsRedirection();
app.UseStaticFiles();
RESTful Web API.
Web API is mostly used for CRED (Create, Read, EDIT, DELETE)
operations.
Front End Back End
Html .Net
JavaScript
Read Operation
Fetch
Sql
Create Operation Database
Angular Server
Response Update Operation
Delete Operation
Android
Maui
……….
State in Web Applications via API
Staying at the same page
Front End
API Controller
fetch(StoreItem Url,Data) Data
Data
StoreItem
Response(“successes message”)
fetch(getItems Url) DB
getItems
Response.Data(JSON Arrau)
Data
REST API Sending Data Types
http://localhost
Body – JSON object
Body – FormData-
Client (image) Server
HTML Page Query string - ?id .Net API
JavaScript Controller
Parameter - /id
Sending data using REST API Methods
Examples
JavaScript API Fetching Methods
examples
fetch("http://localhost:5113/Test/
GET Single Record http://
Id")
localhost
fetch("http://localhost:5113/Test")
GET LIST of Records
Client
HTML Page
fetch("http://localhost:5092/
JavaScript POST Test",option) Server
JSON Object .Net API
Controller
fetch("http://localhost:5092/ Test?Id
PUT ",option)
fetch("http://localhost:5092/ Test?Id
DELETE
",option)
Sending data using REST API Methods Examples
JavaScript API Fetching Methods .Net server API methods Examples
examples http://localhost
Test API Controller
fetch("http://localhost:5092/Test/”+Id) [HttpGet("{id}")]
GET Single Record
public Get(int
parameter
id)
[HttpGet]
GET LIST of Recordsfetch("http://localhost:5092/Test") public Get()
default
fetch("http://localhost:5092/ [HttpPost]
POST json Test",option) public Post([FromBody] class obj )
fetch("http://localhost:5092/
POST [HttpPost] Server
Test",option) API
json public Post([FromBody] List<class>
Controller
array objlst)
fetch("http://localhost:5092/ [HttpPost]
POST Test",option) public Post([FromForm])
image
[HttpPut("{id}")]
fetch("http://localhost:5092/
PUT Test/”+Id) ,option) public Put(int id,
json [FromBody])
DELETE fetch("http://localhost:5092/ Test/”+Id) [HttpDelete("{id}")]
",option) public Delete(int id)
Java script Fetch Example
options = {
method: ‘xx', Post/Put/Delete
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(xx) JSON Object/List of Objects
//or body: xx formData (image)
}
fetch("http://localhost:5092/......",options)
Response: Receiving data Examples
http://localhost
API Controller
public IEnumerable<class> Get()
{List<class> objlst = new
await JSON Array List<class>(); GET LIST of Records
response.json(); ……
return objlst
JSON
Client
HTML Page public class Get(int id)
{class obj = new class();;
await ……
GET Single Record
er
response.text(); return (obj)
String
public string Post(
………. POST DELETE PUT
return (“successfull”)
Creating .Net API Project
You can Add your Api code here in this section
Example 1: Get Method to get all phone records using list of objects
Example 1: Get Method to get all phone records using list of objects
1-create people class
Client Side Server Side
Parameter ?
Input:?
Option ?
Body ? Method :?
sql = "select * from phones";
output :?
Example 1: Get Method to get all phone records using list of objects
1-create people class
Client Side
Server Side
Parameter No Input: none
Option No
Body No [HttpGet]
sql = "select * from phones";
output: list of JSON object
WeatherForecast
2- Create this html page Make sure to copy the
port number from your application
<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<div id="res"></div>
<button type="button" onclick="loadDoc()">Request All Phone</button>
<table border="1" id="demo"></table>
<script>
async function loadDoc() {
var qUrl = "http://localhost:52335/WeatherForecast/";
let myObject = await fetch(qUrl);
let myText = await (myObject.json());
var table = "<tr><th>Name</th><th>Phone</th></tr>";
for (i = 0; i < myText.length; i++) {
table += "<tr><td>" +
myText[i].name + "</td><td>" +
myText[i].phone + "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
3-Create Api code Code at the WeatherForcast Controller
// GET api/values
[HttpGet]
public IEnumerable<pepole> Get()
{ Return list of json object
List<pepole> li = new List<pepole>();
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=mynewdb;Integrated
Security=True");
string sql;
sql = "select * from phones";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
li.Add(new pepole
{
name = (string)reader["username"],
phone = (string)reader["userphone"],
});
}
reader.Close();
conn.Close();
return li;
}
Testing API (not easy)
1- you can use the Swagger tool to test the API within VS Studio
result
2- If swagger is working fine then the server side code is correct 2- then run the clien
3- if the client is not working then insert a breakpoint
3- If the program reach this breakpoint it means the javascript fetch is working fine and it
is calling the API correctly
4-then Step into first line to check if the values received from the client are correct or not
5- if the program did not reach the break point then there is error in javascript code (use
the inspect and debugger to find the error)
Example 2: Get Method to get a single phone record
Example 2: Get Method to get a single phone record
Client Side Server Side
Parameter ? Input:?
Option ? API
Body ? ?
sql = "SELECT * FROM phones where username ='" + name + "' ";
output: ?
Example 2: Get Method to get a single phone record
Server Side
Client Side
Input: name
Parameter name
Option No API
[HttpGet("{name}")]
Body No sql = "SELECT * FROM phones where username ='" + name + "' ";
output: JSON object
[HttpGet("{name}")]
public pepole Get(string name)
{
SqlConnection conn1 = new SqlConnection("Data
Source=.\\sqlexpress;Initial Catalog=mynewdb;Integrated
Security=True;Pooling=False");
string sql;
sql = "SELECT * FROM phones where username ='" + name + "' ";
SqlCommand comm = new SqlCommand(sql, conn1);
conn1.Open();
SqlDataReader reader = comm.ExecuteReader();
pepole pp = new pepole();
if (reader.Read())
{
pp.phone = (string)reader["userphone"];
pp.name = (string)reader["username"];
reader.Close();
conn1.Close();
return (pp);
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
name: <input type="text" id="myNa"> <br>
Phone: <div id="res"></div>
<button type="button" onclick="getphone()">Request Phone</button>
<script>
async function getphone() {
var nn = document.getElementById('myNa').value;
var qUrl = "http://localhost:5167/WeatherForecast/"+nn;
let response = await fetch(qUrl);
let myText = await response.json();
document.getElementById("res").innerHTML = myText.name + " number is "+ myText.phone;
}
</script>
</body>
</html>
Example 3: POST Method to Insert a phone record
Example 3: POST Method to Insert a phone record
Client Side Server Side
Parameter ? Input: :?
Option ?
Body ?
API
Method :?
insert into phones (username,userphone)
values ('" + nn + "','" + pp + "' )";
output: :?
Example 3: POST Method to Insert a phone record
Server Side
Input: JSON object(name, phone)
Client Side
Parameter no
API
[HttpPOST]
Option POST insert into phones (username,userphone)
values ('" + nn + "','" + pp + "' )";
Body JSON(name,
phone)
output: string successful message
[HttpPost]
public string Post([FromBody] pepole ph)
{
var nn = ph.name; Shortcut for mapping form fields to people object
var pp = ph.phone;
To receive JSON object from the form
SqlConnection conn1 = new SqlConnection("Data
Source=.\\sqlexpress;Initial Catalog=mynewdb;Integrated Security=True");
string sql;
sql = "insert into phones (username,userphone) values ('" + nn
+ "','" + pp + "' )";
SqlCommand comm = new SqlCommand(sql, conn1);
conn1.Open();
comm.ExecuteNonQuery();
conn1.Close();
return ("phone Successfully added ");
}
<html lang="en">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<body>
Name : <input type="text" id="myName"> <br>
Phone: <input type="text" id="myPhone"> <br>
<div id="res"></div>
<button type="button" onclick="savephone()">Add Phone</button>
<script>
async function savephone() {
var nn = document.getElementById('myName').value;
var pp = document.getElementById('myPhone').value;
user = { name: nn , phone: pp }
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
}
let response = await fetch("http://localhost:5092/WeatherForecast",options);
let myText = await response.text();
Swal.fire({ icon: 'success', title: myText,showConfirmButton: false,timer: 3000
})
}
</script> Sweet alert to show A basic message show for a limited time (Toast)
</body> For more examples at https://sweetalert2.github.io/
</html>
Example 4: PUT Method to Update a phone record
Example 4: PUT Method to Update a phone record
Client Side
Parameter ?
Option ?
Body ?
Server Side
Input: :?
API
Method :?
update phones set userphone = '" + pa + "', username = '" + na
+ "' where id = '" + id + "'
output: :?
Example 4: PUT Method to Update a phone record
Client Side
Parameter Id
Option PUT
Body JSON(name,
phone)
Server Side
Input: JSON object(name, phone) + Id parameter
API
[HttpPut("{id}")]
update phones set userphone = '" + pa + "', username = '" + na
+ "' where id = '" + id + "'
output: string successful message
[HttpPut("{id}")]
public string Put(int id, [FromBody] pepole ph)
{
var nn = ph.name;
var pp = ph.phone;
SqlConnection conn1 = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True");
string sql;
sql = "update phones set userphone = '" + pp + "', username = '" + nn + "'
where id = '" + id + "' ";
SqlCommand comm = new SqlCommand(sql, conn1);
conn1.Open();
comm.ExecuteNonQuery();
conn1.Close();
return ("phone Sucessfully updated ");
}
<html lang="en">
<body>
Id : <input type="text" id="myId"> <br>
Name : <input type="text" id="myName"> <br>
Phone: <input type="text" id="myPhone"> <br>
<div id="res"></div>
<button type="button" onclick="savephone()">Update</button>
<script>
async function savephone() {
var aa = document.getElementById('myId').value;
var nn = document.getElementById('myName').value;
var pp = document.getElementById('myPhone').value;
user = { name: nn , phone: pp }
let options = {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
}
let response = await fetch("http://localhost:5092/WeatherForecast/"+ aa,options);
let myText = await response.text();
document.getElementById("res").innerHTML = myText;
}
</script></body></html>
Using API within the BookStore Project:
Creating Cascading List Search using API (faster access)
Note that Using API will allow fast get results without the need to submit the entire form
Use Onchange event for
Filling book titles according to the selected category
1
https://youtu.be/SDjqhxRQrs4
Adding books API Controller to the BookStore Project:
• Add new books API Controller
• Also add mybook class
public class mybook
{
public int Id { get; set; }
public string title { get; set; }
}
using Microsoft.AspNetCore.Mvc; • Add this code in order to get all books titles
using System.Data.SqlClient;
according to a specific category
namespace WebApplication4.Controllers
{
[Route("[controller]")]
[ApiController]
public class BookController : ControllerBase
{
// getting all book search catagory
[HttpGet("{cat}")]
public IEnumerable<mybook> Get(int cat)
{
List<mybook> li = new List<mybook>();
// SqlConnection conn1 = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
var builder = WebApplication.CreateBuilder();
string conStr = builder.Configuration.GetConnectionString("WebApplication7Context");
SqlConnection conn1 = new SqlConnection(conStr);
string sql;
sql = "SELECT * FROM book where category ='" + cat + "' ";
SqlCommand comm = new SqlCommand(sql, conn1);
conn1.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
li.Add(new mybook
{
title = (string)reader["title"],
});
reader.Close();
conn1.Close();
return li;
}
• Add this code in order to get all books titles
according to a specific category
Right Click searchall action and add
a view with a detail Template
public async Task<IActionResult> searchall()
{
{
book brItem = new book();
return View(brItem);
}
}
[HttpPost]
public async Task<IActionResult> SearchAll(string tit)
{
var bkItems = await _context.book.FromSqlRaw("select * from book where title = '"
+ tit + "' ").FirstOrDefaultAsync();
return View(bkItems);
}
}
@model WebApplication8.Models.book • Add this code in searchall view
@{
ViewData["Title"] = "searchall";
}
<h1>searchall</h1>
<form asp-action="SearchAll">
<div class="form-group">
</div>
<div class="form-group">
<label class="control-label">Select Catagory</label>
<select class="form-control" name="cata" id="ca" onchange= "gettitle()">
<option value="0">Please select</option>
<option value="1">Computer Science</option>
<option value="2">Information Technology</option>
</select>
</div>
<div class="form-group">
<label class="control-label">Select Title</label>
<select class="form-control" name="tit" id="ti" > </select>
</div>
<input type="submit" value="Show" class="btn btn-default" />
</form> Filling the select items with fetch
<script> result (book titles)
async function gettitle() {
var cc = document.getElementById('ca').value;
var response = await fetch('/books/' + cc); No need to specify the full API path
let x = await response.json();
since it is called at the same server
var dd = "<option> Please select</option>";
for (i = 0; i < x.length; i++) { This fetch will call the get API method
dd += "<option>" + x[i].title + "</option>"; and pass the category parameter
}
document.getElementById("ti").innerHTML = dd;
}
</script>
<div>
<h4>book</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.title)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.title)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.description)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.description)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.price)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.price)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.cata)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.cata)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.image)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.image)
</dd>
Add this code to searchall page to
Display the searched book detail when select the book title