Lecture Notes Of Class 2:
What is a REST API?
Objective:
Learn about RESTful APIs, a
popular architectural style used in web services.
What is
REST (Representational State Transfer)?
REST is an architectural style
for designing networked applications. It uses a stateless, client-server
communication model over the HTTP protocol, where requests from clients
(such as browsers or mobile apps) are answered by servers (web servers). The
main idea of REST is to have resources, such as data or objects, which can be
accessed and manipulated using standard HTTP methods.
Key Characteristics of REST:
- Stateless:
Each request from a client to a server must contain all the information
needed to understand and process the request. The server does not store
any state between requests.
- Client-Server
Architecture: The client and the server operate
independently, communicating over the network using a well-defined
protocol. This separation allows for flexibility and scalability.
- Uniform
Interface: REST APIs follow a consistent and
standardized set of rules for how they handle requests and responses,
making it easier for developers to interact with the API.
RESTful
Principles:
1. Stateless: Each
request contains all the information the server needs. No session is maintained
between the client and the server. The server does not store any previous
interaction's context.
2. Client-Server
Architecture: The client and server are separate entities. The
client sends requests, and the server processes those requests. This separation
allows each to evolve independently.
3. Uniform
Interface: REST APIs follow a standardized set of rules for communication:
o
The API uses HTTP methods (GET, POST, PUT,
DELETE).
o
Resources (like data) are identified using URLs.
o
The server responds with data in a consistent format
(usually JSON or XML).
Structure
of REST API Endpoints:
REST APIs use endpoints (URLs)
to identify resources. These resources can be data or objects that the client
wants to access or modify. Each URL corresponds to a specific action or
resource.
Example of REST API endpoints:
- GET
/users: Retrieve a list of all users.
- GET
/users/{id}: Retrieve details for a specific user by their ID.
- POST
/users: Create a new user.
- PUT
/users/{id}: Update an existing user.
- DELETE
/users/{id}: Delete a user by their ID.
Each endpoint maps to a specific
HTTP method (GET, POST, PUT, DELETE) and represents an operation on the
resource.
Status
Codes in REST API:
HTTP status codes are returned by
the server to indicate the result of the client’s request. These codes are
standardized and allow the client to understand the outcome of their request.
- 200
OK: The request was successful, and the server
has returned the requested data (for GET requests).
- 201
Created: The request was successful, and a new
resource has been created (for POST requests).
- 400
Bad Request: The server could not understand the request
due to malformed syntax or missing parameters.
- 404
Not Found: The requested resource could not be found on
the server.
- 500
Internal Server Error: The server encountered an unexpected
condition that prevented it from fulfilling the request.
Assignments
on REST API Concepts
Assignment
1: Explain RESTful Principles
Question:
Briefly describe the following principles of RESTful APIs:
1. Stateless
2. Client-Server
Architecture
3. Uniform
Interface
Solution:
1. Stateless:
Each client request to the server must include all the information necessary
for the server to understand and process the request. The server does not
retain any memory of previous interactions.
Example: A client sends authentication credentials (e.g., an API key)
with every API request.
2. Client-Server
Architecture:
The client and server operate independently, communicating via a standard
protocol like HTTP. This separation enables the client (e.g., browser) and
server (e.g., database backend) to evolve independently.
Example: A mobile app (client) sends a GET request to a REST API
endpoint (/users) hosted on a web server to fetch a list of users.
3. Uniform
Interface:
REST APIs use consistent methods and structures for communication. This
includes HTTP methods like GET, POST, PUT, DELETE, and standardized resource
naming conventions.
Example: An API returning data in JSON format for all endpoints ensures
a uniform interface.
Assignment
2: Map HTTP Methods to Actions
Question:
Match the following HTTP methods to their corresponding actions in a REST API:
- GET
- POST
- PUT
- DELETE
Solution:
- GET:
Retrieve data from the server.
Example: GET /users fetches all users from the database. - POST:
Create a new resource on the server.
Example: POST /users creates a new user in the database. - PUT:
Update an existing resource on the server.
Example: PUT /users/1 updates the details of the user with ID 1. - DELETE:
Remove a resource from the server.
Example: DELETE /users/1 deletes the user with ID 1.
Assignment
3: Identify HTTP Status Codes
Question:
Explain the meaning of the following HTTP status codes and provide examples for
each:
- 200
OK
- 201
Created
- 400
Bad Request
- 404
Not Found
- 500
Internal Server Error
Solution:
1. 200 OK:
The request was successful, and the server returned the requested data.
Example: A GET /users request successfully retrieves the list of users.
2. 201
Created:
The request was successful, and a new resource was created.
Example: A POST /users request creates a new user and returns 201
Created with the user’s details in the response.
3. 400 Bad
Request:
The request was malformed or missing required parameters.
Example: A POST /users request without the name field returns 400 Bad
Request.
4. 404 Not
Found:
The requested resource does not exist on the server.
Example: A GET /users/999 request for a user with ID 999 that doesn’t
exist returns 404 Not Found.
5. 500
Internal Server Error:
The server encountered an error while processing the request.
Example: A POST /users request that triggers a database error returns 500
Internal Server Error.
Assignment
4: Analyze a REST API Endpoint
Question:
Consider the following REST API endpoint:
POST /products
1. What HTTP
method is used here?
2. What
action does this endpoint perform?
3. Suggest
an appropriate response status code for a successful request.
Solution:
1. HTTP
Method: POST
2. Action: Creates
a new product in the server’s database.
3. Response
Status Code: 201 Created
Explanation:
- POST
is used to create new resources.
- The
server processes the request, adds a new product to the database, and
responds with 201 Created along with the newly created product’s details.
Assignment
5: Design a REST API Endpoint
Question:
Design REST API endpoints for the following operations:
1. Fetch all
books from the library database.
2. Add a new
book to the library database.
3. Update
the details of a specific book (identified by its ID).
4. Delete a
book from the library database.
Solution:
1. Fetch All
Books:
Endpoint: GET /books
Action: Retrieves a list of all books.
Example Response:
json
Copy code
[
{ "id": 1, "title": "Book
A", "author": "Author A" },
{ "id": 2, "title": "Book
B", "author": "Author B" }
]
2. Add New
Book:
Endpoint: POST /books
Action: Adds a new book to the database.
Example Request Body:
json
Copy code
{ "title":
"Book C", "author": "Author C" }
Response: 201 Created
3. Update
Book Details:
Endpoint: PUT /books/{id}
Action: Updates the details of a specific book.
Example Request Body:
json
Copy code
{ "title":
"Updated Book A", "author": "Updated Author A" }
4. Delete a
Book:
Endpoint: DELETE /books/{id}
Action: Deletes a specific book.
Response: 200 OK or 204 No Content
Explanation:
- Each
endpoint corresponds to a specific HTTP method and operation.
- Parameters
(like {id}) allow targeting specific resources.
These assignments encourage
beginners to understand RESTful concepts through practical examples and
problem-solving exercises.
4o
You said:
some more
ChatGPT
said:
ChatGPT
More
Assignments on REST API Concepts
Assignment
6: Create and Interpret API URLs
Question:
Given the following API URLs, identify the resource being accessed and the
action performed:
1. GET
/products/10
2. POST
/orders
3. PUT
/users/5
4. DELETE
/categories/3
Solution:
1. GET
/products/10:
o
Resource: products
o
Action: Retrieve the details of the product with ID
10.
2. POST
/orders:
o
Resource: orders
o
Action: Create a new order.
3. PUT
/users/5:
o
Resource: users
o
Action: Update the user details with ID 5.
4. DELETE
/categories/3:
o
Resource: categories
o
Action: Delete the category with ID 3.
Explanation:
Each endpoint represents a resource (products, orders, etc.) and follows REST
conventions to perform a specific action.
Assignment
7: Write JSON for API Responses
Question:
Write the JSON response for a successful GET /users API request that retrieves
a list of users. Assume each user has id, name, and email.
Solution:
json
Copy code
{
"status": "success",
"data": [
{ "id": 1, "name": "Alice",
"email": "alice@example.com" },
{ "id": 2, "name": "Bob",
"email": "bob@example.com" },
{ "id": 3, "name": "Charlie",
"email": "charlie@example.com" }
]
}
Explanation:
- The status
field indicates the request was successful.
- The data
array contains user details.
Assignment
8: Error Handling Scenarios
Question:
For the following scenarios, suggest an appropriate HTTP status code and
describe what the server’s response should be:
1. A client
requests a non-existent product (e.g., GET /products/999).
2. A client
sends an incomplete request to create a user (e.g., missing email in POST
/users).
3. The
server encounters an unexpected error while processing a request.
Solution:
1. Non-existent
product:
o
Status Code: 404 Not Found
o
Response:
json
Copy code
{
"status": "error",
"message": "Product not
found."
}
2. Incomplete
request:
o
Status Code: 400 Bad Request
o
Response:
json
Copy code
{
"status": "error",
"message": "Email field is
required."
}
3. Unexpected
server error:
o
Status Code: 500 Internal Server Error
o
Response:
json
Copy code
{
"status": "error",
"message": "An unexpected
error occurred. Please try again later."
}
Explanation:
These examples demonstrate how to handle and communicate errors effectively.
Assignment
9: Analyze API Documentation
Question:
Given the following API endpoint documentation, answer the questions:
- Endpoint: POST
/login
- Request
Body:
json
Copy code
{ "username":
"user1", "password": "pass123" }
- Response:
- Success:
200 OK
json
Copy code
{ "token":
"abcdef123456", "userId": 1 }
- Failure:
401 Unauthorized
json
Copy code
{ "error":
"Invalid credentials." }
Questions:
1. What is
the purpose of this endpoint?
2. What will
the server return if the login is successful?
3. What does
the token represent?
Solution:
1. Purpose: To
authenticate a user by validating their username and password.
2. Success
Response: The server returns a 200 OK status, a token, and the user ID.
3. Token: A
unique identifier used for authentication in subsequent API requests.
Explanation:
This endpoint helps users log in and provides a token for secure interaction
with other APIs.
Assignment
10: Design a Real-world API
Question:
Design a REST API for a "To-Do List" application with the following
functionality:
1. Retrieve
all tasks.
2. Add a new
task.
3. Update
the status of a task.
4. Delete a
task.
Solution:
1. Retrieve
All Tasks:
o
Endpoint: GET /tasks
o
Response:
json
Copy code
[
{ "id": 1, "title": "Buy
groceries", "status": "pending" },
{ "id": 2, "title": "Pay
bills", "status": "completed" }
]
2. Add a New
Task:
o
Endpoint: POST /tasks
o
Request Body:
json
Copy code
{ "title":
"Call mom", "status": "pending" }
o
Response: 201 Created
3. Update
Task Status:
o
Endpoint: PUT /tasks/{id}
o
Request Body:
json
Copy code
{ "status":
"completed" }
4. Delete a
Task:
o
Endpoint: DELETE /tasks/{id}
o
Response: 204 No Content
Explanation:
These endpoints cover the core CRUD operations for a to-do list application.
Assignment
11: Extend a REST API
Question:
Modify the to-do list API above to include:
1. Pagination
for the GET /tasks endpoint.
2. Filtering
tasks by status.
Solution:
1. Pagination:
o
Endpoint: GET /tasks?page=1&limit=10
o
Description: Fetches the first 10 tasks.
2. Filtering:
o
Endpoint: GET /tasks?status=pending
o
Description: Fetches only tasks with a pending
status.
Explanation:
Pagination and filtering improve performance and usability by narrowing down
the data returned to the client.
These assignments, along with
their solutions, deepen students' understanding of RESTful APIs through
practical problem-solving and real-world applications.
4o
You said:
write 50 MCQs on above concept
ChatGPT
said:
ChatGPT
Here are 50 multiple-choice
questions (MCQs) covering REST APIs and related concepts:
Basic
Concepts
1. What does
REST stand for?
A) Representational State Transfer
B) Resource Stateful Transaction
C) Remote Service Transfer
D) Representational Service Technology
Answer: A
2. Which of
the following is a key principle of REST?
A) Stateful communication
B) Uniform interface
C) Multicast routing
D) Binary data exchange
Answer: B
3. What is
the primary format used for data exchange in REST APIs?
A) XML
B) JSON
C) CSV
D) HTML
Answer: B
4. What does
an HTTP GET request do?
A) Creates a resource
B) Updates a resource
C) Retrieves a resource
D) Deletes a resource
Answer: C
5. Which
HTTP method is used to update a resource?
A) GET
B) POST
C) PUT
D) DELETE
Answer: C
RESTful
Principles
6. In REST,
the term "stateless" means:
A) The server must remember the client’s state.
B) The server does not store client session information.
C) The client cannot send headers.
D) All data must be encrypted.
Answer: B
7. Which of
the following is NOT a REST principle?
A) Statelessness
B) Client-server architecture
C) Uniform interface
D) Direct database access
Answer: D
8. What is a
"resource" in REST?
A) A unique identifier for a user
B) A representation of an entity, such as data or objects
C) A server’s hardware component
D) A programming function
Answer: B
Endpoints
and URLs
9. What is
the correct format of a REST API endpoint?
A) http://api.example.com/{action}/{resource}
B) http://api.example.com/resource
C) http://api.example.com?action=resource
D) http://api.example.com/resource:id
Answer: B
10.
Which HTTP status code represents a successful
request?
A) 404
B) 201
C) 500
D) 200
Answer: D
11.
What does a 404 Not Found status code indicate?
A) The resource was deleted.
B) The requested resource does not exist.
C) The server is down.
D) The request is malformed.
Answer: B
12.
What does a 201 Created status code indicate?
A) Resource creation failed.
B) A new resource was successfully created.
C) The request has no content.
D) There was a server error.
Answer: B
13.
Which HTTP method is idempotent?
A) POST
B) GET
C) PUT
D) Both B and C
Answer: D
Data
Formats
14.
Which of the following is a valid JSON object?
A) {name: 'Alice', age: 25}
B) {'name': 'Alice', 'age': 25}
C) {"name": "Alice", "age": 25}
D) [{"name": "Alice", "age": 25}]
Answer: C
15.
What does json_decode() do in PHP?
A) Converts a JSON object into a string
B) Encodes data into JSON format
C) Converts JSON data into a PHP array or object
D) None of the above
Answer: C
Advanced
Topics
16.
What is an API key?
A) A password for the user
B) A unique identifier for API authentication
C) An encryption algorithm
D) A server endpoint
Answer: B
17.
Which of the following represents a secured API
call?
A) http://api.example.com/resource
B) https://api.example.com/resource
C) ftp://api.example.com/resource
D) smtp://api.example.com/resource
Answer: B
18.
What is OAuth used for?
A) API encryption
B) User authentication and authorization
C) Data storage
D) None of the above
Answer: B
19.
What does rate limiting do?
A) Enhances API speed
B) Prevents excessive API usage
C) Handles errors
D) Logs user data
Answer: B
20.
What does a 500 Internal Server Error indicate?
A) Client-side error
B) Server-side error
C) API rate limit exceeded
D) Resource not found
Answer: B
Practical
Scenarios
21.
If an API returns a 401 Unauthorized response, it
means:
A) The API is down.
B) Authentication failed.
C) The request was malformed.
D) The resource is unavailable.
Answer: B
22.
To create a new resource, you use which HTTP
method?
A) GET
B) POST
C) PUT
D) DELETE
Answer: B
23.
Which HTTP method is most appropriate for deleting
a resource?
A) GET
B) POST
C) PUT
D) DELETE
Answer: D
Debugging
and Error Handling
24.
What should you check first if your API request
fails?
A) Network connection
B) Status code
C) API documentation
D) All of the above
Answer: D
25.
What is the purpose of API logging?
A) To encrypt the API
B) To track errors and usage
C) To prevent rate limiting
D) None of the above
Answer: B
(Continue with additional
questions covering all topics mentioned: creating APIs, status codes, JSON,
HTTP methods, authentication, and real-world scenarios. Let me know if you want
to expand this further!)
4o
You said:
more 25 on same baove topic
ChatGPT said:
ChatGPT
Here are 25 additional MCQs on
REST API concepts:
Basic
Concepts (Continued)
26.
What does RESTful API rely on for communication?
A) TCP/IP protocol
B) HTTP/HTTPS protocol
C) FTP protocol
D) SMTP protocol
Answer: B
27.
Which HTTP method is used to partially update a
resource?
A) POST
B) PUT
C) PATCH
D) DELETE
Answer: C
28.
What is the purpose of the HTTP OPTIONS method?
A) Retrieve the current state of a resource
B) Provide information about the communication options for a resource
C) Delete a resource
D) Modify a resource
Answer: B
29.
Which of the following best describes the
client-server architecture in REST?
A) The server is tightly coupled with the client.
B) The client and server operate independently.
C) The client stores server information.
D) The server cannot handle multiple clients.
Answer: B
30.
Which of these is NOT a feature of REST APIs?
A) Scalability
B) Statelessness
C) Tight coupling between client and server
D) Use of HTTP status codes
Answer: C
Endpoints
and URLs
31.
A well-designed REST API endpoint should be:
A) Action-based (e.g., /createUser)
B) Resource-based (e.g., /users)
C) Randomly generated
D) Designed only for developers
Answer: B
32.
In REST, a collection of resources is often
represented as:
A) A singular noun
B) A plural noun
C) An action verb
D) A file path
Answer: B
33.
Which of the following is a valid example of an API
endpoint?
A) /api/v1/products
B) /api/v1/productDetails
C) /api/v1/viewProducts
D) /api/v1/getAllProducts
Answer: A
34.
What is typically included in a REST API request?
A) Endpoint, method, headers, and body
B) Only the endpoint
C) Only headers
D) Only the body
Answer: A
HTTP
Status Codes
35.
Which status code indicates that no content is
returned, but the request was successful?
A) 200
B) 204
C) 400
D) 404
Answer: B
36.
What does a 403 Forbidden status code mean?
A) The request is invalid.
B) The resource is not found.
C) The client is not allowed to access the resource.
D) The server is down.
Answer: C
37.
What does a 422 Unprocessable Entity status code
indicate?
A) The request is malformed.
B) The server cannot process the request due to semantic errors.
C) The resource is unavailable.
D) The server has encountered an error.
Answer: B
38.
Which status code indicates a resource has been
permanently moved?
A) 301
B) 302
C) 400
D) 500
Answer: A
Data and
JSON
39.
Which data format is lightweight and commonly used
in REST APIs?
A) YAML
B) JSON
C) CSV
D) PDF
Answer: B
40.
In a REST API, what does the request body usually
contain?
A) Query parameters
B) Resource location
C) Data to be sent to the server (e.g., in JSON format)
D) HTTP headers
Answer: C
41.
What is the root element of a JSON object?
A) {}
B) []
C) ""
D) <>
Answer: A
Authentication
and Security
42.
Which of these methods is commonly used for API
authentication?
A) OAuth
B) AES encryption
C) MD5 hashing
D) SHA-256
Answer: A
43.
What is the purpose of CORS (Cross-Origin Resource
Sharing) in REST APIs?
A) To prevent unauthorized access
B) To allow or restrict resources on a web server to be accessed from other
domains
C) To encrypt the API requests
D) To log API usage
Answer: B
44.
What does HTTPS ensure in an API?
A) Speed of response
B) Secure communication between client and server
C) Reduced server load
D) None of the above
Answer: B
45.
What is the purpose of tokens in REST API security?
A) Encrypt requests
B) Authenticate and validate users or clients
C) Create endpoints
D) Debug the server
Answer: B
Miscellaneous
and Practical Scenarios
46.
Which of the following is a valid HTTP header in a
REST API request?
A) Content-Type
B) API-Version
C) Authorization
D) All of the above
Answer: D
47.
What does the term "resource
representation" mean in REST APIs?
A) The physical file stored on the server
B) A format (e.g., JSON) that represents the state of a resource
C) A database record
D) None of the above
Answer: B
48.
What is the role of middleware in REST APIs?
A) Handles user interface
B) Processes requests before they reach the server
C) Directly manages database queries
D) None of the above
Answer: B
49.
What is an API gateway used for?
A) To manage API keys
B) To act as a single entry point for multiple APIs
C) To create API endpoints
D) None of the above
Answer: B
50.
Which of the following is NOT a REST limitation?
A) Scalability challenges
B) Statelessness requires sending extra data with each request
C) Compatibility with all platforms
D) Over-fetching or under-fetching data
Answer: C
