How to make your own API

How to make your own API

Basic API Development

I hope you know what an API is. If not, then API is Application Programming Interface used by the client-side server to send a request and get a response from server side server

Recipe :

  1. Open your text editor (VS Code or Atom) and open a new folder.

  2. Add an index.js file and a JSON file. I will be making a movies API so I will be making a file named movies.json.

  3. In the terminal which has been opened in the code editor, install these packages via npm or yarn, I will be using npm ( I hope you have installed npm, if not refer to this link npmjs.com/package/download ).

     npm init
     npm install express
    
  4. In the movies.json file, add the movie titles you want to include for your API. If you don't know what JSON is refer to this w3schools.com/js/js_json_intro.asp

     [
         {
             "id":1,
             "movies":"Pathaan"
         },
         {
             "id":2,
             "movies":"KGF"
         },
         {
             "id":3,
             "movies":"RRR"
         },
         {
             "id":4,
             "movies":"Avengers"
         },
         {
             "id":5,
             "movies":"Tiger Zinda Hai"
         },
         {
             "id":6,
             "movies":"Kantara"
         },
         {
             "id":7,
             "movies":"Interstellar"
         }
     ]
    
  5. In the index.js file add this code

     const express = require('express')
     const app = express()
     const port = 3000
     const fs = require('fs')
     app.get('/', (req, res) => {
         res.end('Hello World!');
     });
     app.get("/list_movies", (req, res) => {
         fs.readFile(__dirname + '/' + 'movies.json', (err, data) => {
             res.end(data);
         });
     });
     app.listen(port, () => {
         console.log(`app listening at http://localhost:${port}`)
     });
    
  6. Now if you run the local host with the extension of the /list_movies [ http://localhost:3000/list_movies ]

    Similarly, if you run the server link in Postman you will get a status code of 200 OK

Congratulations, you have made your own API! Voila