Web Services And Web
API
WEB Service [Link]
• A web service is a web-based functionality accessed using the 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).
• These are built around the Web browser standards and can mostly be
used by any browser on any platform (XML HTML)
Service Composition
Application Servers
2 Hotel
Reservation
1
System
4
3
Holiday
Reservation Service
Flight
Front End
Reservation
System
Service Composition
Web service can be used to:
tools: calendar, chat, etc
Information providers: weather, news, flight information
Web API
What is Web API?
web API is an application programming interface for a web
application. It uses HTTP protocol to communicate between
clients and web application to have data access.
How to create an [Link] core web API?
Visual Studio 2017
How to create an [Link] core web API?
Visual Studio 2022
RESTful Web API.
Web API is mostly used for CRED (Create, Read, EDIT, DELETE) operations.
• HTTP GET – Read Operation
• HTTP POST – Create Operation
• HTTP PUT – Update Operation
• HTTP DELETE – Delete Operation
[Link]
fetch([Link] method:
“Get”) API
Controller(Weather
HTML Page
Forcast)
return text or JSON object Action (Get)
/WeathrForcast
/WeathrForcast/1
/WeathrForcast
/WeathrForcast/1
/WeathrForcast/1
var builder = [Link](args);
// Add services to the container.
string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
[Link]();
// Learn more about configuring Swagger/OpenAPI at
[Link]
[Link]();
[Link]();
[Link](o =>
{
[Link]("_myAllowSpecificOrigins", p =>
[Link]().AllowAnyMethod().AllowAnyHeader()
);
});
var app = [Link](); 1-Enabling CORS (Cross Origin Resource
// Configure the HTTP request pipeline. Sharing)
if ([Link]()) To allow remote communication
{
[Link](); Add all red code to the startup file
[Link]();
}
[Link]();
[Link]();
[Link](MyAllowSpecificOrigins);
[Link]();
[Link]();
[HttpGet]
public string[] Get()
{
List<string> list = new List<string>();
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);
[Link]();
SqlDataReader reader = [Link]();
while ([Link]()) Run the Application
{
[Link]((string)reader["username"]);
}
[Link]();
[Link]();
return [Link](); ;
}
To import SqlClient libray
Example 1 Using Get Method to get All Names
<!DOCTYPE html>
<html lang="en">
<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 = "[Link]
let myObject = await fetch(qUrl);
let myText = await ([Link]());
Make sure to copy the
var table = "<tr><th>Name</th></tr>";
for (i = 0; i < [Link]; i++) { port
number from your application
table += "<tr><td>" +
myText[i] + "</td></tr>";
}
[Link]("demo").innerHTML = table;
}
</script>
WeatherForecast
</body>
3-Run the html
</html> File
Example 2 create this Get Method to get all phone records
<!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 = "[Link]
let myObject = await fetch(qUrl);
let myText = await ([Link]());
var table = "<tr><th>Name</th><th>Phone</th></tr>";
for (i = 0; i < [Link]; i++) {
table += "<tr><td>" +
myText[i].name + "</td><td>" +
myText[i].phone + "</td></tr>";
}
[Link]("demo").innerHTML = table;
}
</script>
</body>
</html>
// GET api/values
[HttpGet]
public IEnumerable<pepole> Get()
{
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);
[Link]();
SqlDataReader reader = [Link]();
while ([Link]())
{
[Link](new pepole
{
name = (string)reader["username"],
phone = (string)reader["userphone"],
});
}
[Link]();
[Link]();
return li;
}
Example 3 Using Get/parmeter Method to get a phone record
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
id: <input type="text" id="myId"> <br>
Phone: <div id="res"></div>
<button type="button" onclick="getphone()">Request Phone</button>
<script>
async function getphone() {
var nn = [Link]('myId').value;
var qUrl = "[Link]
let myObject = await fetch(qUrl);
let myText = await [Link]();
[Link]("res").innerHTML = myText;
}
</script>
</body>
</html>
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
SqlConnection conn1 = new SqlConnection("Data
Source=.\\sqlexpress;Initial Catalog=mynewdb;Integrated Security=True");
string sql;
sql = "SELECT * FROM phones where id ='" + id + "' ";
SqlCommand comm = new SqlCommand(sql, conn1);
[Link]();
SqlDataReader reader = [Link]();
string ss, ps;
if ([Link]())
{
ps = (string)reader["userphone"];
ss = ps;
}
else
{ ss = "nouser"; }
[Link]();
[Link]();
return ss;
}
Example 4 Using POST Method to Insert a phone record
<html lang="en">
<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 = [Link]('myName').value;
var pp = [Link]('myPhone').value;
user = { name: nn , phone: pp }
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link](user)
}
let response = await fetch("[Link]
let myText = await [Link]();
[Link]("res").innerHTML = [Link] + " is added";
}
</script>
</body>
</html>
[HttpPost]
public Phones Post([FromBody] Phones ph)
{
var nn = [Link]; Shortcut for mapping form fields to phone object
var pp = [Link];
To receive JSON object from the form f
SqlConnection conn1 = new SqlConnection("Data
Source=.\\sqlexpress;Initial Catalog=mynewdb;Integrated Security=True");
string sql;
sql = "insert into phones (username,userphone) values ('" + n
+ "','" + pp + "' )";
SqlCommand comm = new SqlCommand(sql, conn1);
[Link]();
[Link]();
[Link]();
var result = new Phones { name = nn, phone = pp };
return (result);
}
Example 4 Using PUT Method to Update a phone record
<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 = [Link]('myId').value;
var nn = [Link]('myName').value;
var pp = [Link]('myPhone').value;
user = { name: nn , phone: pp }
let options = {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: [Link](user)
}
let response = await fetch("[Link] aa,opti
let myText = await [Link]();
[Link]("res").innerHTML = [Link] + " is updated";
[HttpPut("{id}")]
public Phones Put(int id, [FromBody] Phones ph)
{
var nn = [Link];
var pp = [Link];
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);
[Link]();
[Link]();
[Link]();
var result = new Phones { name = nn, phone = pp };
return (result);
}
Example 5 Using POST Method to Insert a Book record with image
Create book table
Create Image and wwwroot
folder
<html> <body>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" name="title" class="form-control" id="ti" />
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" name="description" id="de" />
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number" name="price" class="form-control" id="pr" />
</div>
<div class="form-group">
<label class="control-label">Catagory</label>
<select class="form-control" name="cata" id="ca">
<option value="0">Please select</option>
<option value="1">Computer Science</option>
<option value="2">Information Technology</option>
</select>
</div>
<br><img src="" alt="" id="mm" width="150px"><br>
<div class="form-group">
<label>Select picture:</label>
<input type="file" name="file_pic" class="form-control"
accept="image/png, image/jpeg">
</div>
<button onclick="save()">Save</button>
<div id="res"></div>
<script>
async function save() {
var ti = [Link]('ti').value;
var de = [Link]("de").value;
var pr = [Link]("pr").value;
var ca = [Link]("ca").value;
var input = [Link]('input[type="file"]')
var data = new FormData()
[Link]('upfile', [Link][0]);
[Link]('title', ti);
[Link]('description', de);
[Link]('price', pr);
[Link]('cata', ca);
let options = {
method: 'POST',
body: data
}
let response = await
fetch("[Link]
let message = await [Link]();
[Link]("res").innerHTML = message;
}
</script>
</body> </html>
[HttpPost]
public IActionResult Post(IFormFile upfile, [FromForm] string title, [FromForm] string
description, [FromForm] int price, [FromForm] int cata)
{
var ti = title;
var de = description;
var pr = price;
var ca = cata;
To receive Data from the posted form
var im = "";
if (upfile != null)
{
string filename = [Link];
string path = [Link]([Link]([Link](),
"wwwroot\\images"));
using (var filestream = new FileStream([Link](path, filename),
[Link]))
{ [Link](filestream); }
im = filename;
}
SqlConnection conn1 = new SqlConnection("Data Source=.\\sqlexpress;Initial
Catalog=mynewdb;Integrated Security=True;Pooling=False");
string sql;
sql = "insert into book (title,description, price, cata, image) values ('" + ti +
"','" + de + "','" + pr + "' ,'" + ca + "' ,'" + im + "' )";
SqlCommand comm = new SqlCommand(sql, conn1);
[Link]();
[Link]();
[Link]();
return Ok("Book Sucessfully Added");
}