Professional Documents
Culture Documents
Awt - 3
Awt - 3
1
////////////////////////////////////////////////////////////////////////////////
RESTFUL SERVICES
1. **Resource-Based**: RESTful services revolve around resources, identifiable
through URIs, representing any named information. Each URI uniquely
identifies a resource within the system
2. **Uniform Interface**: RESTful services offer a consistent interface using
standard HTTP methods like GET, POST, PUT, DELETE, etc. These methods
perform actions on resources, ensuring predictability and interoperability
across different systems.
3. **Client-Server Architecture**: RESTful services adhere to a client-server
architecture, maintaining a clear separation between the client and server
entities. This architecture enhances scalability and facilitates independent
evolution of both clients and servers.
4. **Stateless**: In RESTful services, every client request to the server must
contain all necessary information (HTTP Method, Resource URI, Request
Headers, Request Body, Query Parameters) for the server to process it. This
stateless nature enhances scalability and simplifies implementation by
eliminating the need for the server to store client state between requests.
5. **Representation**: Resources within RESTful services are commonly
represented in formats such as JSON (JavaScript Object Notation) or XML
(eXtensible Markup Language), enabling easy consumption and interpretation
by clients.
6. **State Transfer**: RESTful services transfer state between client and server
in the form of resource representations. Through these representations, clients
and servers communicate and exchange data, maintaining the statelessness
principle of REST architecture.
Here is the proper response with the numbering, URI, and function for each
method:
1. **GET**
- **URI:** `/movies`
2
- **Function:** Gets the list of all movies and their details.
2. **GET**
- **URI:** `/movies/1234`
- **Function:** Gets the details of Movie id 1234.
3. **POST**
- **URI:** `/movies`
- **Function:** Creates a new movie with the details provided. Response
contains the URI for this newly created resource.
4. **PUT**
- **URI:** `/movies/1234`
- **Function:** Modifies movie id 1234 (creates one if it doesn't already
exist). Response contains the URI for this newly created resource.
5. **DELETE**
- **URI:** `/movies/1234`
- **Function:** Movie id 1234 should be deleted, if it exists. Response should
contain the status of the request.
6. **DELETE or PUT**
- **URI:** `/movies`
- **Function:** Should be invalid. DELETE and PUT should specify which
resource they are working on.
///////////////////////////////////////////////////////////////////////////////
Q 2] Route Parameters
1. **Express.js Route Parameters: Overview**
In Express.js, route parameters are placeholders within the URL pattern of a
route that match specific parts of the URL. They are defined by prefixing a
colon (:) followed by the parameter name in the route's path. Express.js then
3
extracts the values of these parameters from the URL and makes them
accessible in the `req.params` object. The names of route parameters must
consist of "word characters" ([A-Za-z0-9]).
2. **Example Route Parameter Usage**
In this example:
- The route `/users/:userId` defines a route parameter named `userId`.
- When a request is made to a URL like `/users/123`, Express.js extracts the
value `123` from the URL and stores it in `req.params.userId`.
- You can then access the value of the route parameter `userId` within the
route handler function `(req, res) => {...}` using `req.params.userId`.
5
These routes respond with different content when accessed with a GET
request. For example, accessing `/contact` will return "Contact", and accessing
`/about` will return "About page".
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
6
- In a PUT request, the client sends a request to the server, specifying the
resource it wants to update and providing the new data for that resource in the
request body.
- The request typically includes a content-type header to indicate the type of
data being sent in the request body. The URL specifies the location of the
resource to be updated.
4. **Response:**
- The server responds to a PUT request with a status code indicating the
outcome of the request. Common status codes include 200 OK for a successful
update, 201 Created for a successful creation of a new resource, or 204 No
Content for a successful update with no response body.
- The response may include additional information about the updated
resource or any changes made to it.
5. **Example Code:**
This code snippet demonstrates how to handle POST requests in Express.js. It
uses the `body-parser` middleware to parse the incoming request bodies and
defines a route `/submit` to handle POST requests. Inside the route handler, it
accesses the data sent in the request body, processes it, and responds to the
client with a success message.
7
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
8
function in the application’s request-response cycle. The next middleware
function is typically denoted by a variable named `next`.
9
5. **Third-party Middleware**: Created by third-party libraries to extend
Express.js functionality, such as authentication, authorization, rate limiting, etc.
Added to an Express.js application using npm packages.
6. **Custom Middleware**: Developed by developers to perform specific
tasks required by their application, such as logging, authentication,
authorization, request validation, etc.
///////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////
10
1. **Purpose:**
HTTP DELETE requests are used to instruct the server to delete a specified
resource.
2. **HTTP Method:**
DELETE is one of the HTTP methods defined in the HTTP protocol. It is
idempotent, meaning that making the same request multiple times should
have the same effect as making it once
3. **Request Structure:**
- In a DELETE request, the client sends a request to the server to delete the
specified resource.
- The URL specifies the location of the resource to be deleted.
4. **Response:**
- The server responds to a DELETE request with a status code indicating the
outcome of the request. Common status codes include `200 OK` for a
successful deletion or `204 No Content` for a successful deletion with no
response body.
5. **Express.js Example:**
Here's how you can handle DELETE requests in Express.js:
11
Explanation:
- We define a route `/resource/:resourceId` to handle DELETE requests,
where `:resourceId` is a route parameter capturing the ID of the resource to be
deleted.
- Inside the route handler, we extract the `resourceId` from `req.params`.
- We then perform the logic to delete the resource, which might involve
interacting with a database or any other data source.
- Finally, we send an appropriate response based on whether the deletion
was successful or not.
///////////////////////////////////////////////////////////////////////////////////
///////////
12
Q 7] **Nodemon Overview:**
Nodemon is a utility for Node.js-based applications that automatically
restarts the Node application when file changes in the directory are detected.
This feature streamlines the development process by eliminating the need to
manually restart the server after making code changes.
2. **Installation:**
**Global Installation:**
- **Command:** `npm install -g nodemon`
- **Purpose:** Installs Nodemon globally on your system, enabling you to
use it as a command-line tool across all projects.
- **Usage:** You can run any Node.js application using Nodemon from any
directory without specifying its path.
**Local Installation:**
- **Command:** `npm install --save-dev nodemon`
- **Purpose:** Installs Nodemon locally within the project directory, making
it a dependency of the project.
- **Usage:** Nodemon becomes part of the project's dependencies and can
be managed via the project's `package.json` file. This approach is beneficial for
isolating dependencies for different projects and avoiding potential conflicts.
13
4. **Best Practices:**
- It's generally recommended to use local installation for Nodemon, especially
in projects with multiple contributors or when working on different projects
simultaneously. This approach facilitates dependency management and
minimizes the risk of conflicts.
Q 8] Restful Services
Creating RESTful services in Express.js involves designing APIs that adhere to
the principles of Representational State Transfer (REST). RESTful services allow
clients to perform CRUD (Create, Read, Update, Delete) operations on
resources using standard HTTP methods (GET, POST, PUT, DELETE).
Here's a structured guide on how to create RESTful services in Express.js
1. **Define Routes:**
Define routes for your API endpoints corresponding to different CRUD
operations. Typically, these routes map to specific HTTP methods and perform
corresponding actions on resources.
14
2. **Implement Controller Logic:**
Implement the logic for CRUD operations within the route handlers. This logic
typically involves interacting with a database, processing data, and sending
appropriate responses.
15
3. **Integrate Middleware:**
Integrate middleware functions as needed for tasks such as request
validation, authentication, and error handling.
16
4. **Test the API:**
Test your API endpoints using tools like Postman or curl to ensure they
function as expected and follow REST principles.
By following these steps, you can create robust and scalable RESTful services in
Express.js for building web applications and APIs. Remember to adhere to
RESTful design principles and keep your APIs simple, consistent, and resource-
oriented.
To create a RESTful service in Express.js, you typically define routes for each
HTTP method and map them to corresponding controller functions that handle
the business logic. For example:
17
In this example, we define routes for retrieving, creating, updating, and
deleting users. The URI `/api/users` represents the resource of users, and HTTP
methods are used to perform corresponding actions on that resource. This
adheres to the RESTful principles, making the API predictable and easy to use.
18