0% found this document useful (0 votes)
2 views16 pages

Web II Handling Requests and Responses Lesson005

The document outlines the process of handling HTTP requests and responses between clients and servers, detailing how clients send requests, servers process them, and responses are sent back. It also introduces Postman as a tool for API testing, explaining how to configure requests and interpret responses. Additionally, it provides examples of Express.js server setup, route handling, and controller functions for managing user data through API endpoints.

Uploaded by

komendominic3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Web II Handling Requests and Responses Lesson005

The document outlines the process of handling HTTP requests and responses between clients and servers, detailing how clients send requests, servers process them, and responses are sent back. It also introduces Postman as a tool for API testing, explaining how to configure requests and interpret responses. Additionally, it provides examples of Express.js server setup, route handling, and controller functions for managing user data through API endpoints.

Uploaded by

komendominic3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

HANDLING HTTPS REQUESTS AND RESPONSES

Handling HTTP requests and responses involves a client (like a web browser)
sending a request to a server, which then processes the request and sends back a
response.
The client and server exchange data through HTTP messages, which can be in the
form of text or binary.
Here's a breakdown of the process:
1. Client Sends a Request:
 The client initiates the connection to the server.
 It sends an HTTP request, which includes information like the requested
URL, HTTP method (GET, POST, etc.), and any headers or data.
2. Server Processes the Request:
 The server receives the request.
 It processes the request based on the URL, HTTP method, and any other
parameters.
 It might query a database, perform calculations, or access other resources to
generate a response.
3. Server Sends a Response:
 The server creates an HTTP response.
 The response includes a status code (e.g., 200 OK, 404 Not Found), headers,
and the data that the client requested.
 The server sends the response back to the client.
4. Client Receives and Processes the Response:
 The client receives the response from the server.
 It parses the response, extracting information like the status code, headers,
and data.
 It uses the received information to update the user interface or perform other
actions.
Example Scenario:
Imagine you type a website address into your browser (the client).
1. Client: The browser sends an HTTP GET request to the server, requesting
the web page.
2. Server: The web server receives the request and finds the corresponding
web page.
3. Server: The server sends an HTTP response containing the web page data
and a status code (e.g., 200 OK).
4. Client: The browser receives the response and displays the web page.
Key Concepts:
 HTTP Methods:
Common methods include GET (retrieve data), POST (create data), PUT
(replace data), PATCH (update data), and DELETE (delete data).
 Status Codes:
Indicate the success or failure of the request (e.g., 200 OK, 404 Not Found, 500
Internal Server Error).
 Headers:
Provide additional information about the request or response, such as content
type, cookies, and authentication details.

NOTE: In essence, HTTP request and response is the fundamental mechanism


for communication between web clients and servers, enabling the exchange of
information that powers the internet.
Postman Working, HTTP Request & Responses
As a developer you know the importance of API in any kind of application. In
simple terms, API is a defined set of rules with some defined methods of
communication. With the help of API, software components can interact with
each other.
Implementing a quality API is really important to ensure fast development
without compromising on the code quality. The best and popular tool for API
testing among developers is Postman.
How Postman Works?
Postman provides easy-to-use interace for sending http request and receiving
responses form the web servers and APIs. Postman working includes the
following steps:
 The http request are created by defining http method, URL, headers, body.
 This request is sent by the postman to the server or API endpoint.
 Then server's response is received and displayed by Postman including the
response status, header and body
Postman sends the request to the webserver and then the server sends the
response back to it. A user has to set all the headers and cookies API expects to
check the response.
Configure the Request
You can select one of the methods from the given dropdown list. You will also
have to include more information depending on the API call.
This information is set as Authorization, Header, or body information. You just
need to select one of the methods and send the request and get the response
back.
Your API call mainly uses two things...
1. HTTP Request
You make HTTP calls sending the HTTP Request. In HTTP Request method
includes Request Method, Request URL, Request Headers, Request Body,
Pre-request Script, and Tests.
Let's talk about these Request methods one by one...
Request Methods
You will find several types of Request methods in POSTMAN. Depending on
your requirements or test you can choose one of them. Mainly you will be using
four request methods in your application. These methods are given below...
 GET Request: To retrieve or fetch data
 POST Request: To create and update data
 PUT Request; To update data
 DELETE Request: For deleting data
Request URL: You will find a long-width bar in Postman where you will have
to enter the URL to make the HTTP request.
Request Headers: In the request header, you enter the key value of the
application. The two main key values are given below.
 Content-Type: The format of data is specified by Content-Type. Mainly
developers use JSON format in the content type.
 Authorization: This information is included to identify the requester.
Request Body: In Postman, you will get the tab of Body where you can
mention some specific information that needs to be sent with the request. You
will get the option to send the data either in raw, binary, or any other form. Most
of the time you will select raw form. You will also get the option of Pre-request
scripts. This gets executed before a request is sent. In Postman, you are also
allowed to write and run the test for each request. You can use JavaScript
language for this.
2. HTTP Response
Once you send the request to Postman, you get the response back from the API
that contains Body, Cookies, Headers, Tests, Status Code, and API Response
time. Body and Header get organized in different tabs. Status code gets
displayed in another tab with the time taken to complete the API call. Some
important status codes are given below to verify the response.
 200- For successful request.
 201- For successful request and data was created
 204- For Empty Response
 400- For Bad Request.
 401- For Unauthorized access. Authentication failed or the user does not
have permission for the requested operation.
 403- For Forbidden, Access Denied
 404- For data not found.
 405- For method not allowed or requested method is not supported.
 500- Internal server error.
 503- For Service unavailable

EXAMPLE

Server.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/users');
app.use(express.json());
// Use routes
app.use('/api/users', userRoutes);
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

Route/user.js
const express = require('express');
const router = express.Router();
const usersController = require('../controllers/users');

router.get('/', usersController.getUsers);

router.post('/', usersController.createUser);

router.get('/:id', usersController.getUserById);

module.exports = router;

controllers/user.js
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];

// GET /api/users
const getUsers = (req, res) => {
res.json(users);
};
// POST /api/users
const createUser = (req, res) => {
const { name, email } = req.body;

if (!name || !email) {
return res.status(400).json({
error: 'Both name and email are required'
});
}

// Generate new ID (max existing ID + 1)


const newId = users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1;
const newUser = { id: newId, name, email };

users.push(newUser); // Add to the shared array


res.status(201).json(newUser);
};

// GET /api/users/:id
const getUserById = (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);

if (!user) {
return res.status(404).json({ error: 'User not found' });
}

res.json(user);
};

module.exports = {
getUsers,
createUser,
getUserById
};

Testing in Postman
A. GET All Users (GET /api/users)
1. Open Postman and create a new request.
2. Set Request Type: GET
3. Enter URL: http://localhost:3000/api/users
4. Click "Send"

5. Expected Response:
[
{ "id": 1, "name": "John Doe", "email": "john@example.com" },
{ "id": 2, "name": "Jane Smith", "email": "jane@example.com" }
]

B. GET Single User (GET /api/users/:id)


1. New Request in Postman.
2. Set Request Type: GET
3. Enter URL: http://localhost:3000/api/users/1
4. Click "Send"
5. Expected Response:
{
"id": 1,
"name": "User 1",
"email": "user1@example.com"
}

C. POST Create User (POST /api/users)


1. New Request in Postman.
2. Set Request Type: POST
3. Enter URL: http://localhost:3000/api/users
4. Go to the "Body" tab:
o Select raw
o Choose JSON from the dropdown
5. Enter JSON Data:
{
"name": "Alice Brown",
"email": "alice@example.com"
}

Expected
Endpoint Method URL Body (JSON)
Response

Get all users GET /api/users - Array of users

/api/
Get user by ID GET - Single user
users/1

Create user { "name": "...",


POST /api/users 201, user data
(success) "email": "..." }

{ "name":
Create user 400, error
POST /api/users "..." } (missing
(error) message
email)
QUERY PARAMETERS
A query parameter in Express.js is a way to pass data to the server through the
URL.
These parameters are appended to the end of the URL after a question mark ? and
are represented as key-value pairs, separated by ampersands &.
Express.js provides the req.query object to access these parameters within route
handlers.
For example, consider the following URL:
/search?q=javascript&page=2
In this URL, q and page are query parameters with
values javascript and 2 respectively.
To access these parameters in an Express.js route handler, you can use req.query:
app.get('/search', (req, res) => {
const searchTerm = req.query.q;
const page = req.query.page;

// Use searchTerm and page to perform search and pagination


res.send(`Searching for: ${searchTerm} on page ${page}`);
});
In this example, req.query.q retrieves the value of the q parameter,
and req.query.page retrieves the value of the page parameter.
Query parameters are commonly used for: Filtering and sorting data, Pagination,
Passing optional data to an API, and Modifying the behavior of a route.
It's important to note that query parameters are optional and do not affect the route
matching process. They simply provide additional information to the server.
CONTROLLERS
A controller in Express. js is a module or function that handles the logic when a
route is called.
Instead of writing all the logic inside the route definition, controllers allow you to
offload that functionality to separate files.

Controllers/users.js
// Define users array OUTSIDE the functions (shared across all routes)
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];

// GET /api/users
const getUsers = (req, res) => {
// Access query parameters
const { name, email,} = req.query;

let filteredUsers = [...users];

// Filter by name if provided


if (name) {
filteredUsers = filteredUsers.filter(user =>
user.name.toLowerCase().includes(name.toLowerCase())
);
}

// Filter by email if provided


if (email) {
filteredUsers = filteredUsers.filter(user =>
user.email.toLowerCase().includes(email.toLowerCase())
);
}

res.json(filteredUsers);
};

// POST /api/users
const createUser = (req, res) => {
const { name, email } = req.body;

if (!name || !email) {
return res.status(400).json({
error: 'Both name and email are required'
});
}

// Generate new ID (max existing ID + 1)


const newId = users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1;
const newUser = { id: newId, name, email };

users.push(newUser); // Add to the shared array


res.status(201).json(newUser);
};

// GET /api/users/:id
const getUserById = (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);

if (!user) {
return res.status(404).json({ error: 'User not found' });
}

res.json(user);
};

module.exports = {
getUsers,
createUser,
getUserById
};
Server.js
const express = require('express');
const app = express();

// Import routes
const userRoutes = require('./routes/users');

// Middleware to parse JSON requests


app.use(express.json());

// Use routes
app.use('/api/users', userRoutes);

// Starting the server


const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

Router/user.js
const express = require('express');
const router = express.Router();
const usersController = require('../controllers/users');
// GET /api/users
router.get('/', usersController.getUsers);

// POST /api/users
router.post('/', usersController.createUser);

// GET /api/users/:id
router.get('/:id', usersController.getUserById);

module.exports = router;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy