0% found this document useful (0 votes)
46 views

2023-S1-SE3040-Lecture-05-REST and Express

The document provides an overview of REST services and the Express JS framework. It discusses key REST concepts like HTTP methods and status codes. It also covers how to set up an Express JS application, define routes, and use middleware. The goal is to help readers understand RESTful APIs and how to build them using Express JS.

Uploaded by

My Soulmate
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

2023-S1-SE3040-Lecture-05-REST and Express

The document provides an overview of REST services and the Express JS framework. It discusses key REST concepts like HTTP methods and status codes. It also covers how to set up an Express JS application, define routes, and use middleware. The goal is to help readers understand RESTful APIs and how to build them using Express JS.

Uploaded by

My Soulmate
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

REST Services and Express JS Thusithanjana

Thilakarathna
Learning Outcomes
• Understand the concept of RESTful web
services and how they work
• Understand the HTTP methods used in RESTful
services (GET, POST, PUT, DELETE)
• Understand the different HTTP status codes
and their meanings
• Know how to interpret HTTP responses using
status codes
• Understand the basics of Express.js framework
• Be able to create and configure an Express.js
server
• Understand how to use middleware in
Express.js to enhance their API's functionality.

2
Web Sever and Web Service

On the other hand, a web service is a software


A web server is a computer program that is system that allows different applications to
responsible for handling incoming requests from communicate with each other over the internet
clients, such as web browsers, and serving them or intranet using standardized protocols, such as
with the appropriate resources, such as HTML SOAP or REST. Web services are typically used to
pages, images, and other web assets. The primary expose data or functionality that can be
function of a web server is to deliver content to consumed by other applications, regardless of
web clients over the internet or intranet. their programming language or platform. Web
Examples of web servers include Apache, Nginx, services can be consumed by a wide range of
and IIS. clients, such as web browsers, mobile apps, or
other web services.

3
Introduction to REST API

REST APIs allow clients to


REST (Representational State interact with server-side
Transfer) is an architectural resources over the internet
style for building web services using HTTP methods (GET,
POST, PUT, DELETE)

Why use REST API? It provides a


REST APIs are widely used for
simple and standardized way to
building web applications and
build scalable and interoperable
mobile apps
systems.

4
REST API Design
Principles
REST APIs should be designed to follow certain principles, such as:
• Using HTTP methods to indicate the type of operation being
performed (GET for reading, POST for creating, PUT for updating,
DELETE for deleting)
• Using meaningful URIs (Uniform Resource Identifiers) to identify
resources (e.g., /users, /products/123)
• Using HTTP status codes to indicate the success or failure of a request
(e.g., 200 OK, 404 Not Found, 500 Internal Server Error)
• Providing a consistent interface for interacting with the API
• Using hypermedia (links) to enable clients to discover and navigate the
API

5
A REST API request typically
consists of:
• HTTP method: The type of operation
Anatomy of being performed (e.g., GET, POST, PUT,
DELETE)
a REST API • URI: The location of the resource being
accessed (e.g., /users, /products/123)
Request • Headers: Additional information about
the request (e.g., Content-Type,
Authorization)
• Body (optional): Data being sent as part
of the request (e.g., JSON payload)

6
A REST API response typically
consists of:
• HTTP status code: Indicates the
REST API success or failure of the request
Response (e.g., 200 OK, 404 Not Found, 500
Internal Server Error)
Format • Headers: Additional information
about the response (e.g., Content-
Type, Cache-Control)
• Body: Data being sent as part of the
response (e.g., JSON payload)

7
HTTP
messages
HTTP codes
9

• HTTP status codes are 3-digit numbers that indicate the status of a client's request to a server.
The first digit of the status code defines the class of response, while the last two digits do not
have any classification role.
• 1xx Informational
• 2xx Success
• 3xx Redirection
• 4xx Client Error
• 5xx Server Error
Commonly used HTTP codes
• 200 OK: The request was successful, and the server has
returned the requested data.
• 301 Moved Permanently: The requested resource has been
permanently moved to a new location, and the client
should update its URL to reflect this change.
• 404 Not Found: The requested resource could not be found
on the server.
• 500 Internal Server Error: There was an error on the server
while processing the request, and the client should try
again later.

10
200 - OK *
201 - Created *
202 - Accepted
204 - No content *

HTTP code 301 - Moved permanently


302 - Found
examples 304 - Not modified *
400 - Bad request *
401 - Unauthorized *
403 - Forbidden *
404 - Not found *
HTTP code examples
• 405 - Method not allowed
• 409 - Conflict *
• 412 - Precondition failed
• 418 – An interesting code check 😉
• 500 - Internal server error *
• 502 - Bad gateway
• 503 - Service unavailable
REST API Authentication
• Authentication is the process of verifying the identity of a
client making a request
• REST APIs can use different authentication mechanisms,
such as:
• Basic authentication: The client sends a base64-encoded
username and password in the Authorization header
• Token-based authentication: The client sends a token (e.g.,
JWT) in the Authorization header
• OAuth 2.0: A protocol for authorization that allows a user to
grant a third-party application access to their resources

13
REST API Versioning
• REST APIs can evolve over time and new versions may
introduce changes that are not backward compatible
• API versioning is the practice of creating different
versions of the API to handle these changes
• Versioning can be done by:
• Using a version number in the URI (e.g., /v1/users)
• Using a version number in the Accept header (e.g.,
Accept: application/json; version=1.0)
• Using content negotiation to select the appropriate
version based on the client's request

14
REST API Best
Practices
Some best practices to follow when designing and implementing REST APIs
include:
• Keeping the API simple and consistent
• Using descriptive and meaningful URIs
• Providing clear documentation and examples
• Avoiding breaking changes in new versions
• Using caching and compression to improve performance
• Monitoring and analyzing usage data to identify issues and optimize the API

15
16
• Express JS is a fast, unopinionated, and
minimalist web framework for Node.js
• It was created in 2010 by TJ Holowaychuk
and is now maintained by the Node.js
Introduction Foundation
• Express JS is widely used for building web
to Express JS applications and APIs
• Why use Express JS? It provides a simple and
flexible way to handle HTTP requests and
responses, making it easy to build scalable
and maintainable applications.

17
• To use Express JS, you need to install it using
npm (Node Package Manager)
• You can create an Express JS application by
Setting up an running the "express" command or by
manually creating the file structure
Express JS • The most important files in an Express JS
application application are "app.js" (or "index.js") and
"package.json"
• You can start an Express JS application by
running "npm start" or "node app.js"

18
Routing in Express JS
• Routing is the process of matching a
URL pattern to a specific piece of
code (a controller)
• In Express JS, you define routes using
the "app.get", "app.post", "app.put",
"app.delete" methods
• You can use parameters in the URL
(e.g., "/users/:id") to pass data to
the controller
• You can also use regular expressions
to match complex URL patterns

19
Middleware in Express
JS
• Middleware is a function that sits
between the client and the server and
can modify the request or response
• Express JS has built-in middleware
functions for handling requests, parsing
data, and serving static files
• You can use third-party middleware
functions for tasks like logging,
authentication, and caching
• You can create your own middleware
functions to handle specific tasks or
modify the request/response as needed

20
Handling errors in Express JS
Express JS provides a default error handling middleware function that
catches errors and sends an appropriate response
You can also create your own error handling middleware function to
customize the error response
There are different types of errors in Express JS, such as 404 errors
(resource not found), 500 errors (server error), and user-defined errors
Handling errors correctly is important for providing a good user
experience and ensuring the stability of your application
21
Templating engines in Express JS

• Templating engines are used to generate HTML pages dynamically


• Express JS supports several popular templating engines, including Pug
(formerly Jade), EJS (Embedded JavaScript), and Handlebars
• You can install a templating engine using npm and then configure it in your
Express JS application
• Templating engines allow you to create reusable templates and pass data
to them from your controllers

22
Working with databases
in Express JS
• Express JS can work with different types of databases,
including SQL databases (e.g., MySQL, PostgreSQL)
and NoSQL databases (e.g., MongoDB)
• You can connect to a database using a database driver
or an ORM (Object-Relational Mapping) library like
Sequelize or Mongoose
• Querying the database is done using SQL or a
database-specific query language (e.g., MongoDB
query syntax)
• ORM libraries provide a higher-level interface for
working with databases and can simplify the code for
common tasks like creating, reading, updating, and
deleting records

23
RESTful APIs with Express JS
• A RESTful API is an API that follows the REST (Representational State
Transfer) architecture style
• Express JS is well-suited for building RESTful APIs because of its routing and
middleware capabilities
• To create a RESTful API, you define routes that correspond to the different
HTTP methods (GET, POST, PUT, DELETE) and the resources you want to
expose
• You can use middleware functions to handle tasks like input validation,
authentication, and rate limiting
• RESTful APIs should follow certain principles, such as using HTTP status
codes to indicate success or failure, using meaningful URIs to identify
resources, and providing a consistent interface for interacting with the API.

24
Thank you!
References
• https://www.npmjs.com/package/express-basic-auth
• https://www.npmjs.com/package/jsonwebtoken
• https://expressjs.com/en/starter/installing.html
• https://www.javatpoint.com/expressjs-
template#:~:text=A%20template%20engine%20facilitates%20you,to%
20design%20HTML%20pages%20easily.

25

You might also like