RESTful API

What is RESTful API?

  • Representational

  • State

  • Transfer

  1. One form of Software Architecture for Hypermedia systems such as the WWW (World Wide Web)

  2. A REST Server allows clients to access and modify server information using the HTTP Protocol

  3. Information is provided in text, xml, json formats

    • Nowadays json is the mainstream!

HTTP method

4 commonly used methods in REST-based architecture

  1. GET

    : Retrieve

  2. PUT

    : Create and update

  3. DELETE

    : Remove

  4. POST

    : Create

Creating a Database

  • Create a JSON-based user database

Test04_RESTful > data > user.json

1. API: GET/list

  • Create a GET API that outputs all user lists

router > main.js

  • __dirname

    • Represents the location of the current module

    • Since the router module is inside the router folder, you need to use a relative path to access the data folder!

After running the server, access http://localhost/listarrow-up-right

image-20200407040640515

2. API: GET/getUser/:username

  • Create a GET API that retrieves detailed information for a specific username!

Add to router > main.js

  • After reading the file, it finds and outputs the user id

    • If the user is found, it outputs the user data

    • If not found, it outputs {}

  • Since reading a file with fs.readFile() returns the data in text format, you need to use JSON.parse()!

After restarting the server, access http://localhost/getUser/first_userarrow-up-right

image-20200407041513712

3. API: POST addUser/:username

body: { "password": "", "name": "" }

Add to router > main.js

  • Returns an error if the JSON format is Invalid

  • If valid, opens the file, checks for username duplication, then adds to the JSON data and saves again

  • stringify(users, null, 2) is for JSON pretty-print

4. API: PUT updateUser/:username

body: { "password": "", "name": "" }

  • An API that updates user information

  • Uses the PUT method

    • An idempotent PUT API

      • Must guarantee the same result no matter how many times the request is made!

Add to router > main.js

5. API: DELETE deleteUser/:username

  • An API that deletes user data

    • Uses the DELETE method

Add to router > main.js

Last updated