< alishour.dev />

Creating a RESTful API - Part 1 Preview Image

Creating a RESTful API - Part 1

April 19, 2022

Learn how to create a simple RESTful API and connect it to your front-end application in this comprehensive guide.

REST APIs
Node JS
Javascript

3 min read

What is a RESTful API?

An API (Application Programming Interface) is a communication mechanism between two or more services, acting as a mediator between users/clients and the resources/services they request. RESTful APIs specifically follow REST architecture principles, enabling integration with RESTful web services.

Step 1: Initializing a new Project

Begin by creating an empty folder in your preferred directory. You can do this manually or via Terminal/Bash:

mkdir myProject
cd ./myProject

Then set up a new empty npm package using legacy init (-y flag skips the questions):

npm init -y

null
Note: You must have node.js installed on your machine. You can customize the package.json file with your specific information like name, git repo, and description.

Step 2: Installing Dependencies

We'll use a minimal setup with two main packages:

  • express: A minimal Node.js framework to simplify our workload
  • CORS: Handles Cross-Origin-Resource-Sharing

Install these packages using:

npm i express cors

Also install nodemon for development (automatically restarts the application when detecting file changes):

npm i --save-dev nodemon

Step 3: Creating an Entry Point

Create an index.js file in your project root and modify your package.json:

{
  "name": "project-name",
  "version": "1.0.0",
  "description": "Add project description here if you want to",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "node index.js",
    "start-dev": "nodemon index.js"
  },
  "keywords": [],
  "author": "your-name",
  "license": "ISC"
}

Add the following code to your index.js file:

import express from "express"
import cors from "cors"

const app = express()

app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cors())

const port = process.env.PORT || 5000

app.get("/", (req, res) => {
    res.send("Welcome to our new custom API!")
})

app.use((req, res, next) => {
    const error = new Error("Something went wrong")
    error.status = 404
    next(error)
})
app.use((error, req, res, next) => {
    res.status(error.status || 500)
    res.json({
        error: {
            message: error.message,
        },
    })
})

app.listen(port, (err) => {
    if (err) throw new Error("Error while connecting to the server")
    console.log(`Server is live and running at: http://localhost:${port}`)
})

export default app

Start your development server with:

npm run start-dev

Final Thoughts

We've created a basic RESTful API that serves as a foundation for more complex applications. While this implementation is simple, it demonstrates the core concepts of API development. In the next part, we'll expand the functionality and explore database integration.

null
💡 Pro Tip: Consider using environment variables to manage your port numbers and API configurations across different environments (development, staging, production). This makes your API more secure and easier to maintain.

let's discuss
your ideas