In the vast landscape of web development, creating a robust API is a fundamental skill. APIs, or Application Programming Interfaces, serve as the communication bridge between different software applications. Today, we’ll embark on a journey to build a simple blog API using Node.js and the popular Express framework.
What is an API?
An API, or Application Programming Interface, is a set of rules and tools that allows different software applications to communicate with each other. It defines the methods and data formats that applications can use to request and exchange information. APIs play a crucial role in enabling the integration of various services and applications, facilitating interoperability and data exchange.
In simpler terms, an API is like a conversation between a client and a server. The client makes requests by following a set of rules, and the server responds with the requested information or action. It’s a way for different programs to talk to each other and exchange data in an organized manner.
Real-Time Example: Weather API
Imagine you’re developing a weather application, but you don’t have the resources to collect and maintain weather data for every location on your own. This is where a Weather API comes into play.
1. API Provider (Server):
There is a Weather API provider (e.g., OpenWeatherMap, Weatherstack) that collects and updates weather information regularly. This provider exposes an API with specific endpoints and data formats.
2. API Consumer (Client):
You are the developer creating a weather application. Instead of collecting and maintaining your weather data, you decide to use a Weather API to get real-time weather information. Maybe you are lazy to collect information and rather use an API!! (jus kidding)
3. How the API Works:
Your weather application sends an HTTP request to the Weather API’s endpoint, specifying the location (e.g., city or coordinates). The Weather API processes the request, retrieves the current weather data for the specified location, and formats it according to the API’s standards. The API then sends the formatted data back to your application as an HTTP response.
4. Integration in Your Weather App:
Your weather application parses the received data and uses it to display the current weather conditions, temperature, humidity, etc. Users of your application get real-time weather updates without your app having to manage the entire database of weather information.
In this example, the Weather API acts as a bridge between your weather application and the weather data provider, allowing your app to access and display real-time weather information without the complexity of managing the entire data infrastructure. This illustrates how APIs streamline communication and collaboration between different software components.
In this blog, we will set up a new node.js project. Open your terminal and follow the commands! These following commands are to set up a node project.
mkdir nodeProject cd nodeProject npm init -y
Installing Express
Now, we will install express in this project. According to the documentation, Express is a Fast, unopinionated, minimalist web framework for Node.js.
npm install express --save
Set up the Express App
In your project, create a file “index.js”, and lets lay the foundation for your Express app.
const express = require("express"); const app = express(); const port = 3000; app.use(express.json()); // Routes will go here app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
When you run the above code, you will notice that the server runs on the localhost 3000. That’s where the port is mentioned. The code imports the Express framework and assigns it to the variable express
. The express()
function creates an instance of the Express application. This app
object is the central piece of an Express application, and it is used to define routes, middleware, and handle HTTP requests and responses.
The app.use()
function is setting up middleware for the Express application. In this case, it’s using the express.json()
middleware, which parses incoming JSON requests. It makes the parsed JSON data available in req.body
for further processing in your routes.
The comment, “// Routes will go here,” indicates that you should define your routes between the app.use(express.json())
line and the app.listen()
line. Routes define how your server responds to different HTTP requests, such as GET, POST, PUT, or DELETE, for specific endpoints.
Now, we will see how to set up such a CRUD operation in this code.
Before that, we should know the basics of REST API:
For now, we can know the most important technical stuff.
A RESTful API (Representational State Transfer) is an architectural style for designing networked applications. REST is often used in the context of web services to create scalable, lightweight, and maintainable systems. Here are some key concepts and principles associated with RESTful APIs:
Resources: In REST, everything is considered a resource. A resource can be an object, data, or service that can be identified by a unique URI. Examples of resources include user profiles, products, articles, etc. In our code, we have described how to access product value and ids.
HTTP Methods (Verbs): RESTful APIs use standard HTTP methods for communication. The primary HTTP methods used in REST are:
GET
: Retrieve a resource.POST
: Create a new resource.PUT
: Update an existing resource (replace).PATCH
: Update an existing resource (partially).DELETE
: Remove a resource.
URIs (Uniform Resource Identifiers): Resources are identified using URIs. Each resource should have a unique URI that clients can use to interact with it.
For example: /api/users
, /api/products/123
.
Status Codes: HTTP status codes are used to indicate the success or failure of a request. Common status codes include 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request), 404 (Not Found), and 500 (Internal Server Error).
Security: RESTful APIs can use standard HTTP security mechanisms such as HTTPS for secure communication, authentication using API keys or tokens, and authorization based on user roles.
These are the important key concepts to know about RESP API. Now, we will dive into the code. This code is the basic CRUD operation just to access, update, post or delete the products in in-memory.
Tips for node.js: Use nodemon to avoid restarting your server.
const express = require("express"); const app = express(); const port = 3000; app.use(express.json()); const products = [ { id: 1, name: "Ceramic" }, { id: 2, name: "Resin" }, { id: 3, name: "Paraffin Wax" }, ]; // Get all products app.get("/api/products", (req, res) => { res.json(products); }); //get specific product by id app.get("/api/products/:id", (req, res) => { const productId = parseInt(req.params.id); const item = products.find((item) => item.id === productId); if (!item) { return res.status(404).json({ error: "Item not found." }); } res.json(item); }); //post products app.post("/api/products", (req, res) => { const { name } = req.body; if (!name) { return res.status(404).json({ error: "Name is required." }); } const newItems = { id: products.length + 1, name }; products.push(newItems); res.status(201).json(newItem); }); //update products app.put("/api/products/:id", (req, res) => { const itemId = parseInt(req.params.id); const item = products.find((item) => item.id === itemId); if (!item) { return res.status(404).json({ error: " product not found." }); } const { name } = req.body; if (item) { item.name = name; } res.status(200).json(item); }); //delete products app.delete("/api/products/:id", (req, res) => { const itemId = parseInt(req.params.id); const item = products.findIndex((item) => item.id === itemId); if (item == -1) { return res.status(404).json({ error: " product not found." }); } const deleteProduct = data.splice(item, 1)[0]; res.status(200).json(deleteProduct); }); app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
Verify using Postman
Test Your CRUD API: Run your server with node app.js
and use a tool like Postman or curl to test your API endpoints:
- GET (All):
http://localhost:3000/api/products
- GET (Specific):
http://localhost:3000/api/
products
/1 - POST:
http://localhost:3000/api/
(with JSON payload)products
- PUT:
http://localhost:3000/api/
(with JSON payload)products
/1 - DELETE:
http://localhost:3000/api/
products
/1
The best alternative for Postman is also Kong Insomnia, which is a collaborative open source API development platform that makes it easy to build high-quality APIs — without the bloat and clutter of other tools.
This example provides a simple in-memory CRUD API using Express. Depending on your use case, you may want to replace the in-memory data store with a database and add additional features such as validation, authentication, and error handling.
In our next blog, we can see how to integrate a database like SQL and MongoDB.