Share
Explore

s24 June 7 Session 10: Developing an API

1
Session 10: FRI
Peter
Developing an API
What is an API?
Creating an API endpoint with res.json() and MongoDB
Consuming an API in the client using fetch() and res.json()
2
There are no rows in this table
The goal of the JavaScript Web Application is to build an IT Service that enables remote users to access our Business Domain.

The Design Pattern which Web Applications are based on is called the MVC

Model: Back end data persistence and storage : We have been thinking of the “back end” as just data, but it can do processing as well: This would lead to the SOA pattern.
You can watch my video on SOA and microservices as an enrichment topic:
It is an interesting observation that the MVC pattern is one very narrow and specific sub case of S.O.A. is the MVC ! In this case, the Controller is a MONOLITHIC Block containing ALL the algorithm. In SOA, we break this out to many small blocks each of which delivers only one algorithm. Those blocks communicate with each other within their JavaScript runtime environment using TCP/IP.

This observation does lead us into today’s topic which is APIs.
What is an API?
How do we write any program?
We make many objects - And we connect those objects together how exactly?
We connect objects with METHOD CALLS!
So API Application Program Interfaces are just method calls between OBJECTS which live in different run time environments in different Operating Systems on different computers connected via TCPIP.
Something even stronger:
The client application can connect to a server application in totally heterogenous format:
A service is just a METHOD CALL.
So I could make a Python Client - You could be running a Java Runtime Server.
I could get services from your OBJECTS by making Method Calls in a properly formatted way. This can happen because our clients and servers are all coded to observe the correct communication protocols.


Consider: In addition to being a database, the “back end model” could also be an API which is today’s lesson.
View : Point of interaction with the USER / Express.js web server with its routes and end points.
Controller : JS Objects which we write to deliver the business rules and algorithms.

Part 1: Introduction to APIs

1. What is an API?
- An API (Application Programming Interface) is a set of rules that allows different software entities (heterogenous environments) to communicate with each other by the fact that we all work on the same protocols.
- The API is a communication conduit which connects applications to access data or functionality from other applications, services, or platforms.

megaphone

An API can be seen as a method call on an object living in a Node.js runtime on another operating system, which we connect to via TCP/IP.

This perspective can help students grasp the concept of APIs in a more concrete manner, especially if they are familiar with object-oriented programming and method calls within a local environment.


1. Simplified Concept:**
- **Local Method Call:** - Explain how, in a typical program, a method call interacts with an object in memory, executing specific functions and potentially returning data. - Example: `object.method(parameters)`

- **Remote API Call:** - An API call is conceptually similar but occurs over a network. Instead of interacting with an object in the same memory space, it interacts with an object residing on a server.
- Example: `http://api.server.com/resource`

2. Technical Details:
- Node.js Runtime: - The server hosting the API runs a Node.js environment where the API logic is implemented. - The API endpoint is like a method exposed to the outside world, accessible via a specific URL.

TCP/IP Communication:
- The underlying protocol for communication is TCP/IP, enabling reliable data transfer between the client and server.
- HTTP/HTTPS is typically the application layer protocol used on top of TCP/IP for web APIs.

3. Real-World Analogy:
- **Local to Remote Transition:
- Just as a local method call might fetch data from a local database or perform calculations, an API call fetches data from a remote database or performs server-side logic.
- This transition is facilitated by sending a request over the network and receiving a response.

Detailed Example
Local Method Call: ```javascript // Local object and method const database = { getUser: (id) => { return { id: id, name: "John Doe" }; } };
// Calling the method const user = database.getUser(1); console.log(user); // Output: { id: 1, name: 'John Doe' }
Remote API Call: ```javascript // Node.js server exposing an API const express = require('express'); const app = express(); const port = 3000;
app.get('/user/:id', (req, res) => { const user = { id: req.params.id, name: "John Doe" }; res.json(user); });
app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); ```
```javascript // Client making a remote API call fetch('http://localhost:3000/user/1') .then(response => response.json()) .then(data => console.log(data)); // Output: { id: 1, name: 'John Doe' } ```
Conclusion By drawing parallels between local method calls and remote API calls, you gain a clear and relatable understanding of what an API is and how it operates.
This approach demystifies the concept and helps students relate it to something we are already familiar with, making the learning process smoother and more intuitive.

Types of APIs:

Web APIs:
Accessible over HTTP/HTTPS:
RESTful APIs
SOAP APIs [Simple Object Access Protocol]
Library APIs: Provided by libraries to enable specific functionalities within the same application.
Communication protocols are provided by libraries such as the kind we integrate into our JavaScript programs from NPMjs.com
RESTful APIs: - Representational State Transfer (REST) is an architectural style that uses standard HTTP methods. - CRUD operations:
Create (POST), Read (GET), Update (PUT/PATCH), Delete (DELETE).
In the early days: These corresponded to SQL CRUD operations. The early Internet was envisioned as a way to enable remote network access to databases.

Importance of APIs:
- Enable integration between different services and systems. - Promote reusability of functionalities. - Facilitate easier maintenance and scalability of applications. (In my video: I discuss by the SOA is better for application maintenance and scalability).

Lecture Notes:
1. API Basics: - Discuss the concept of APIs with examples (e.g., social media login integrations). - Explain the difference between REST and SOAP. 2. RESTful API Principles: - Stateless interactions, scalability, and resource identification (URI).

3. Example Use Cases:
- Fetching weather data, integrating payment gateways, accessing third-party services like Google Maps.


Part 2: Creating an API Endpoint with res.json() and MongoDB


1. Setting Up the Environment
Tools and Technologies:
- Node.js and Express.js for server-side development.
- MongoDB as the database.
- Postman for testing the API endpoints.

Installation: - Node.js: [Node.js Download](https://nodejs.org/) - MongoDB: [MongoDB Download](https://www.mongodb.com/try/download/community) - Postman: [Postman Download](https://www.postman.com/downloads/)

2. Coding the API

1. **Initialize a Node.js Project:** ```bash mkdir api-project cd api-project npm init -y npm install express mongoose ```
2. Create a Basic Express Server: ```javascript // server.js const express = require('express'); const mongoose = require('mongoose');
const app = express(); const port = 3000;
app.use(express.json());
// MongoDB connection mongoose.connect('mongodb://localhost:27017/apiDB', { useNewUrlParser: true, useUnifiedTopology: true });
// Basic route app.get('/', (req, res) => { res.send('Hello World!'); });
app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

3. Define a Mongoose Schema and Model: ```javascript // models/item.js const mongoose = require('mongoose');
const itemSchema = new mongoose.Schema({ name: String, quantity: Number });
module.exports = mongoose.model('Item', itemSchema);

4. Create API Endpoints:
// server.js (continued) const Item = require('./models/item');
// Create item app.post('/items', async (req, res) => { const newItem = new Item(req.body); await newItem.save(); res.json(newItem); });
// Read items app.get('/items', async (req, res) => { const items = await Item.find(); res.json(items); });
// Update item app.put('/items/:id', async (req, res) => { const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.json(updatedItem); });
// Delete item app.delete('/items/:id', async (req, res) => { await Item.findByIdAndDelete(req.params.id); res.json({ message: 'Item deleted' }); });

Part 3: Consuming an API in the Client using fetch() and res.json()


*1. Introduction to Fetch API
- The Fetch API provides a way to make network requests similar to XMLHttpRequest (XHR).
-Basic Syntax:
fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

Lecture Notes:

1. Understanding Fetch: - Promises, handling JSON responses, error handling.

2. DOM Manipulation: - Updating the DOM with fetched data.

Lab Exercises:

Exercise 4:
Create a simple HTML page to fetch and display data from your API.
Exercise 5:
Implement error handling for the fetch requests.
Exercise 6:
Add functionality to create new items through a form and update the displayed list.


Resources:
- [MDN Web Docs: API](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction)
- [Express.js Documentation](https://expressjs.com/)
- [Mongoose Documentation](https://mongoosejs.com/)
- [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)

megaphone

Further Exercises:




done: NOTE Find a more reliable (but still FREE!) Weather API service

YELP-style Services Rating App:

Bitcoin Coin Converter Service

Done: Lab: Server Static Middleware:
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.