A Web API(Application Programming Interface) is a way for different
software applications to talk to each other over the internet.Think of it like a waiter
in a resturant. You(the client) tell the waiter(the API) what you want to eat, and the waiter
takes your request to the kitchen(the server) and brings back your food(the data).
Why Uses API?
- Access Data & Services: You want to show weather information on your
website. Instead of collecting and updating weather data yourself, you can use a weather API that provides up-to-date
weather data from a reliable resource.
- Save Time and Effort: Instead of writing your own code to handle complex
tasks like payment processing, you can user an API from a payment service provider like
PayPal or Bkash or Nagad.
How Does a Web API Works?
- Client Request: Your application(the client) sends a request to the API
server. This request includes what you want(like fetching weather data for a city)
- Server Response: The API server processes the request and sends back a
response, which includes the data or service you asked for.
- Use the Data: Your application receives the data and you can user it to
display information, perform actions or whatever you need.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jokes App</title>
</head>
<body>
<h1>Random Joke</h1>
<button id="get-joke">Get a Joke</button>
<p id="joke"></p>
<script >
document.getElementById('get-joke').addEventListener('click', function() {
fetch('https://official-joke-api.appspot.com/random_joke')
.then(response => response.json())
.then(data => {
document.getElementById('joke').textContent = `${data.setup} - ${data.punchline}`;
})
.catch(error => {
console.error('Error fetching joke:', error);
});
});
</script>
</body>
</html>