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.
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.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:
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.