Web Services And Web
API
WEB Service asp.net
• 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 Asp.Net core web API?
Visual Studio 2017
How to create an Asp.Net 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
http://localhost
fetch(http://localhost/WeathrForcast, 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 = WebApplication.CreateBuilder(args);
// Add services to the container.
string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
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(); 1-Enabling CORS (Cross Origin Resource
// Configure the HTTP request pipeline. Sharing)
if (app.Environment.IsDevelopment()) To allow remote communication
{
app.UseSwagger(); Add all red code to the startup file
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.Run();
[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);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read()) Run the Application
{
list.Add((string)reader["username"]);
}
reader.Close();
conn.Close();
return list.ToArray(); ;
}
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 = "http://localhost:52335/WeatherForecast";
let myObject = await fetch(qUrl);
let myText = await (myObject.json());
Make sure to copy the
var table = "<tr><th>Name</th></tr>";
for (i = 0; i < myText.length; i++) { port
number from your application
table += "<tr><td>" +
myText[i] + "</td></tr>";
}
document.getElementById("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 = "http://localhost:563719/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>
// 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);
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;
}
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 = document.getElementById('myId').value;
var qUrl = "http://localhost:64946/WeatherForecast/"+nn;
let myObject = await fetch(qUrl);
let myText = await myObject.text();
document.getElementById("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);
conn1.Open();
SqlDataReader reader = comm.ExecuteReader();
string ss, ps;
if (reader.Read())
{
ps = (string)reader["userphone"];
ss = ps;
}
else
{ ss = "nouser"; }
reader.Close();
conn1.Close();
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 = 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:5111/WeatherForecast",options);
let myText = await response.json();
document.getElementById("res").innerHTML = myText.name + " is added";
}
</script>
</body>
</html>
[HttpPost]
public Phones Post([FromBody] Phones ph)
{
var nn = ph.name; Shortcut for mapping form fields to phone object
var pp = ph.phone;
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);
conn1.Open();
comm.ExecuteNonQuery();
conn1.Close();
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 = 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:5111/WeatherForecast/"+ aa,opti
let myText = await response.json();
document.getElementById("res").innerHTML = myText.name + " is updated";
[HttpPut("{id}")]
public Phones Put(int id, [FromBody] Phones 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();
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 = document.getElementById('ti').value;
var de = document.getElementById("de").value;
var pr = document.getElementById("pr").value;
var ca = document.getElementById("ca").value;
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('upfile', input.files[0]);
data.append('title', ti);
data.append('description', de);
data.append('price', pr);
data.append('cata', ca);
let options = {
method: 'POST',
body: data
}
let response = await
fetch("http://localhost:5056/WeatherForecast",options);
let message = await response.text();
document.getElementById("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 = upfile.FileName;
string path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot\\images"));
using (var filestream = new FileStream(Path.Combine(path, filename),
FileMode.Create))
{ upfile.CopyToAsync(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);
conn1.Open();
comm.ExecuteNonQuery();
conn1.Close();
return Ok("Book Sucessfully Added");
}