What are Api's ?
API (Application Programming Interfaces)
APIs are like messengers that let different software talk to each other, defining rules for interaction. They allow developers to access functions of existing software without understanding their inner workings, simplifying development. APIs are pre-built blocks for creating new applications or integrating existing ones. They act as bridges, facilitating seamless communication between different software systems.
Types of Api's?
RESTful APIs: Simple, scalable, and use standard HTTP methods.
SOAP APIs: Robust, structured messaging using XML.
GraphQL APIs: Flexible data fetching for precise requirements.
WebSocket APIs: Enable real-time bidirectional communication.
RPC APIs: Invoke procedures between systems in distributed environments.
Library APIs: Access pre-written functions within software libraries.
External APIs: Integrate third-party services into applications.
How to Create REST Api's?
REST(Representational State Transfer)
Commonly Used Methods
Get
Post
Patch
Delete
// Importing the Require Modules
const express = require('express'); // Express Server
const fs = require('fs'); // Lets u Perform Operations on File(R/W)
const users = require('./MOCK_DATA.json'); // Sample Datas
// Use the Following website to generate random datas in variable exports like JSON,CSV etc
//https://www.mockaroo.com/
const app = express();
const PORT = 8000;
// Middlewares - Plugin
app.use(express.urlencoded({extended: false}));
// Shows the entire users JSON
app.get('/api/users', (req, res) => {
return res.json(users);
});
// Shows the unique user with respective id
app.get('/api/users/:id', (req, res) => {
const id = Number(req.params.id);
const user = users.find((user) => user.id === id);
return res.json(user);
});
// Shows the users to the audience
app.get('/users', (req, res) => {
const html = `
<ul>
${users.map((user) => `<li>${user.first_name}</li>`)}
</ul>
`;
res.send(html);
});
// Add a new user
app.post("/api/users", (req, res) => {
const body = req.body;
users.push({...body, id: users.length + 1});
fs.writeFile("./MOCK_DATA.json", JSON.stringify(users), (err, data) => {
return res.json({status: "success", id: users.length});
});
});
// Delete a user by id
app.delete('/api/users/:id', (req, res) => {
// Delete the user
const id = Number(req.params.id);
const index = users.findIndex(user => user.id === id);
if (index !== -1) {
users.splice(index, 1);
fs.writeFile("./MOCK_DATA.json", JSON.stringify(users), (err, data) => {
return res.json({status: "success", message: `User with id ${id} deleted`});
});
} else {
return res.status(404).json({status: "error", message: `User with id ${id} not found`});
}
});
// Update a user by id
app.patch('/api/users/:id', (req, res) => {
const id = Number(req.params.id);
const body = req.body;
const index = users.findIndex(user => user.id === id);
if (index !== -1) {
// Update the user with new data
users[index] = {...users[index], ...body};
// Rewrite the updated users array to the JSON file
fs.writeFile("./MOCK_DATA.json", JSON.stringify(users), (err) => {
if (err) {
return res.status(500).json({status: "error", message: "Failed to update user data"});
}
return res.json({status: "success", message: `User with id ${id} updated`, updatedUser: users[index]});
});
} else {
return res.status(404).json({status: "error", message: `User with id ${id} not found`});
}
});
app.listen(PORT, () => console.log(`Server started at the port ${PORT}`));