Unit 3: API Development and Server Actions - Subjective Questions
INT257 — Modern Web Application Development • Practice Questions with Detailed Answers
20 questions
Define a route handler in a modern web application framework. Explain its purpose and describe the main steps involved in creating one.
A route handler is a server-side function that receives an HTTP request for a particular URL and returns an HTTP response.
Purpose:
- It connects a URL and HTTP method to server-side application logic.
- It can read request data, access databases or external services, validate input, and return structured responses.
- It is commonly used to implement APIs and backend functionality.
Main steps:
- Create a file in the framework's API or route directory.
- Export functions corresponding to HTTP methods such as
GET,POST,PUT,PATCH, orDELETE. - Read parameters, query strings, headers, or request bodies.
- Perform validation and business logic.
- Return a response with appropriate data, status codes, and headers.
For example, a GET handler may retrieve records from a database and return them as JSON, while a POST handler may validate and store a newly submitted record.
Explain the principles of REST APIs and describe how resources, endpoints, and representations are used in RESTful design.
REST, or Representational State Transfer, is an architectural style for designing networked applications.
Important principles include:
- Resource orientation: Application data is represented as resources such as users, products, or orders.
- Unique endpoints: Each resource or collection is identified by a URL, such as
/api/productsor/api/products/42. - HTTP methods: Standard methods express the intended operation on a resource.
- Statelessness: Every request contains the information required to process it; the server does not depend on stored client session state.
- Representations: Resources are transferred in formats such as JSON.
- Consistent responses: Similar resources should follow consistent naming, status codes, and response structures.
For example, /api/books can represent a collection of books, while /api/books/10 represents one specific book. The same resource can be retrieved, modified, or deleted using different HTTP methods.
Compare the HTTP methods GET, POST, PUT, PATCH, and DELETE with respect to their purposes, safety, and idempotency.
The main HTTP methods differ in the operation they represent:
GET: Retrieves a resource without changing server data. It is safe and idempotent.POST: Creates a new resource or triggers an action. It is generally neither safe nor idempotent because repeating the request may create multiple resources.PUT: Replaces an entire resource at a known URL. It is not safe but is idempotent when implemented correctly.PATCH: Applies a partial update to an existing resource. It is not safe, and idempotency depends on the operation and implementation.DELETE: Removes a resource. It is not safe but is normally idempotent because deleting an already deleted resource leaves the resource absent.
A safe method does not intentionally modify server state. An idempotent method produces the same final server state when the same request is repeated, although the response itself may differ.
Describe dynamic route handlers and explain how route parameters are used to retrieve or modify a specific resource.
A dynamic route handler uses a variable segment in its URL so that one handler can process many related URLs. For example, /api/users/[id] can match /api/users/7 and /api/users/25.
Processing flow:
- The framework extracts the dynamic value, such as
id, from the URL. - The route handler reads that parameter from the route context.
- The parameter is validated and converted to the required type.
- The handler uses it to query, update, or delete the corresponding resource.
- The handler returns an appropriate response if the resource exists or a
404 Not Foundresponse otherwise.
Dynamic routes reduce duplication because a single handler can support all resource identifiers. They should validate parameters carefully to avoid invalid database queries and unintended access to other users' data.
Explain how a server should process an incoming request and construct an appropriate response in a route handler.
A route handler typically follows a request-processing pipeline:
- Identify the request: Determine the HTTP method and matched route.
- Read request information: Access headers, cookies, URL parameters, query strings, and the request body.
- Authenticate and authorize: Verify the identity of the caller and whether the caller may perform the operation.
- Validate input: Check required fields, data types, lengths, formats, and business rules.
- Execute application logic: Read or mutate data through services, repositories, or a database.
- Handle failures: Convert expected failures into meaningful status codes and error messages.
- Construct the response: Return JSON or another representation with headers and a suitable HTTP status code.
Responses should be consistent. A successful retrieval may return 200 OK, a successful creation may return 201 Created, invalid input may return 400 Bad Request, and a missing resource may return 404 Not Found.
Distinguish between path parameters, query parameters, headers, cookies, and request bodies. Give one suitable use case for each.
These request components carry different kinds of information:
- Path parameters: Values embedded in the URL path, such as
/products/15. They identify a specific resource. - Query parameters: Optional values after
?, such as/products?category=books&page=2. They support filtering, searching, sorting, and pagination. - Headers: Metadata about the request, such as authorization tokens, content types, or cache directives.
- Cookies: Small values sent automatically by the browser, often used for sessions, preferences, or authentication state.
- Request bodies: Data submitted with methods such as
POSTorPUT, commonly represented as JSON, form data, or multipart data.
For example, a product request could use a path parameter for the product ID, query parameters for pagination, an authorization header for identity, a cookie for a session identifier, and a request body when updating product details.
Design a REST API for managing students. Specify suitable endpoints, HTTP methods, request data, and response status codes for the main operations.
A suitable student API could use the following design:
GET /api/students: Returns a collection of students. Use200 OK.GET /api/students/{id}: Returns one student. Use200 OKif found or404 Not Foundif absent.POST /api/students: Creates a student from a JSON body such as{ "name": "Asha", "email": "asha@example.com" }. Use201 Createdafter successful creation or400 Bad Requestfor invalid data.PUT /api/students/{id}: Replaces all editable fields of a student. Use200 OKor204 No Contentafter success.PATCH /api/students/{id}: Updates selected fields. Use200 OK,400 Bad Request, or404 Not Foundas appropriate.DELETE /api/students/{id}: Deletes a student. Use204 No Contentafter success or404 Not Foundif the student does not exist.
The API should use consistent JSON structures, validate email and required fields, authenticate protected operations, and avoid exposing sensitive information.
Explain the role of HTTP status codes and describe the status codes most commonly used in API development.
HTTP status codes communicate the result of processing a request to the client. Correct status codes allow clients to respond appropriately without interpreting arbitrary messages.
Common categories and examples:
- 2xx success:
200 OKindicates a successful request,201 Createdindicates that a resource was created, and204 No Contentindicates success without a response body. - 3xx redirection: These codes indicate that further action or a different location may be required.
- 4xx client errors:
400 Bad Requestindicates invalid input,401 Unauthorizedindicates missing or invalid authentication,403 Forbiddenindicates insufficient permission,404 Not Foundindicates a missing resource, and409 Conflictindicates a state conflict. - 5xx server errors:
500 Internal Server Errorindicates an unexpected server failure, while503 Service Unavailableindicates temporary unavailability.
An API should avoid returning 200 OK for every outcome because that hides failures and makes client-side error handling unreliable.
What are server actions? Explain how they differ from conventional client-side event handlers and API route handlers.
A server action is a server-executed function that can be invoked from a user interaction, commonly a form submission or a framework-supported action call.
Characteristics of server actions:
- They execute on the server and can safely access server-only resources.
- They can receive submitted form data or structured arguments.
- They are useful for database mutations, authentication-related operations, and other trusted backend work.
- They can reduce the amount of client-side code needed for simple mutations.
A client-side event handler runs in the browser and is responsible for interaction, local state, and preparing a request. A route handler exposes an HTTP endpoint that can be consumed by browsers, mobile apps, or external clients. A server action is usually a framework-managed server function intended for direct application interactions rather than a general public API contract.
Server actions still require authentication, authorization, validation, and secure handling of submitted data.
Describe the complete lifecycle of handling a form submission with a server action.
A form submission using a server action generally follows these stages:
- The user enters values into form controls.
- The form submits its fields, commonly as a
FormDataobject. - The server action receives the data and extracts the submitted values.
- The action authenticates the user and checks authorization.
- Input values are normalized and validated on the server.
- The action performs the required mutation, such as inserting or updating a database record.
- The action returns a success result, validation errors, or an application error.
- The user interface displays field-level or form-level feedback and updates the relevant data.
Client-side validation can improve responsiveness, but server-side validation is mandatory because client code can be bypassed. The action should also prevent duplicate submissions where necessary and provide accessible pending and error states.
Explain form validation in a web application. Compare client-side validation and server-side validation, and discuss why both may be used.
Form validation verifies that submitted values are complete, correctly formatted, safe, and consistent with application rules.
Client-side validation:
- Runs immediately in the browser.
- Gives fast feedback without a network round trip.
- Can check required fields, input formats, and basic limits.
- Must not be trusted because users can disable or bypass it.
Server-side validation:
- Runs in a trusted server environment.
- Protects databases and business rules from invalid or malicious input.
- Must verify authentication, authorization, types, ranges, uniqueness, and relationships.
- Is the final source of truth for accepting or rejecting a mutation.
Using both provides good user experience and reliable security. Validation errors should be specific, associated with the relevant fields, and returned in a predictable structure.
Develop a validation strategy for a registration form containing a name, email address, password, and password confirmation.
A robust registration validation strategy should validate both individual fields and relationships between fields.
- Name: Require a non-empty value, trim surrounding whitespace, and enforce a reasonable maximum length.
- Email: Require a value, normalize it where appropriate, and verify its general format. The server should also enforce uniqueness.
- Password: Require a minimum length and apply the application's password policy. Passwords must never be stored in plain text; they should be hashed using a suitable password-hashing algorithm.
- Confirmation: Require the confirmation value to match the password exactly.
- Cross-field rules: Check that the email is not already registered and that all required fields are present.
- Security checks: Reject unexpected fields where appropriate, protect the action against cross-site request forgery when required, and avoid revealing whether sensitive accounts exist.
The server should return structured field errors, for example an error associated with email or passwordConfirmation, while the client displays those messages accessibly.
Explain how file uploads work in web applications and describe the purpose of multipart/form-data and FormData.
File uploads send binary file content from the browser to the server. A normal URL-encoded form is not suitable for binary files, so upload forms generally use the multipart/form-data encoding type.
FormData:
- Represents form fields as key-value pairs.
- Can contain strings as well as
Fileobjects. - Is commonly created from a form and submitted through a request or server action.
Server-side processing:
- Read the uploaded file and its metadata.
- Validate size, MIME type, extension, and content where necessary.
- Generate a safe storage name instead of trusting the original filename.
- Store the file in a suitable storage service or controlled filesystem location.
- Store only the required file metadata in the database.
- Return a reference or URL to the client.
Uploads require limits and security controls because files may contain malware, misleading extensions, or resource-exhaustion risks.
Design a secure file-upload workflow for profile images, including validation, storage, error handling, and access control.
A secure profile-image workflow can be designed as follows:
- Accept the upload using
multipart/form-dataand require an authenticated user. - Enforce a maximum file size before processing the complete upload.
- Validate the declared MIME type and inspect file content rather than trusting the filename alone.
- Allow only supported image formats and reject executable or unexpected files.
- Decode and re-encode the image when possible to remove embedded content and normalize dimensions.
- Generate a random storage key; never use the original filename directly as a server path.
- Store files outside executable application directories or use a dedicated object-storage service.
- Save metadata such as owner, storage key, size, and content type in the database.
- Restrict access using ownership checks or signed, time-limited URLs.
- Delete or quarantine partial and rejected uploads.
- Return clear validation errors without exposing internal storage details.
The workflow should also consider rate limits, virus scanning for higher-risk systems, and cleanup of old profile images.
What is a data mutation? Explain the responsibilities of a server action or route handler that creates, updates, or deletes data.
A data mutation is an operation that changes persistent application state. Examples include creating an order, updating a profile, or deleting a comment.
A mutation handler should:
- Authenticate the caller.
- Authorize the specific operation and resource.
- Parse and validate all input on the server.
- Normalize values such as whitespace, dates, and identifiers.
- Check business rules, including uniqueness and valid state transitions.
- Execute the database operation using parameterized queries or a safe ORM.
- Use a transaction when several related writes must succeed or fail together.
- Handle conflicts and missing records explicitly.
- Return a consistent result and suitable status code.
- Invalidate or refresh affected cached data.
- Avoid returning sensitive database fields.
A mutation should be designed to be predictable under retries, concurrent requests, and partial failures.
Explain how authentication and authorization should be applied to API route handlers and server actions.
Authentication determines who is making a request, while authorization determines what that authenticated user is allowed to do.
A protected handler should:
- Retrieve credentials from a secure session, cookie, or authorization header.
- Verify the credential's signature, expiration, and integrity.
- Load the relevant user or account context.
- Check permissions, roles, ownership, or resource-level policies.
- Reject unauthenticated requests with
401 Unauthorized. - Reject authenticated users without sufficient permission with
403 Forbidden. - Perform authorization checks on the server for every sensitive operation.
A handler must not rely on hidden form fields, disabled buttons, or client-side route protection. For example, a user may be allowed to edit their own profile but not another user's profile. The authorization check must use the authenticated identity rather than an identity supplied only by the request body.
Compare route handlers and server actions as mechanisms for implementing data mutations. Include their advantages, limitations, and suitable use cases.
Route handlers:
- Expose explicit HTTP endpoints.
- Are suitable for public APIs, mobile clients, webhooks, and integrations.
- Make HTTP methods, status codes, headers, and response formats explicit.
- Require the developer to design and maintain an API contract.
Server actions:
- Expose server-side functions through framework-managed invocation.
- Are convenient for application-owned forms and tightly coupled user-interface mutations.
- Can reduce boilerplate for request construction and response handling.
- May be less suitable for external consumers or long-lived public API contracts.
Both mechanisms require server-side validation, authentication, authorization, error handling, and protection against duplicate or malicious requests. A route handler is usually preferred when multiple clients need a stable HTTP interface; a server action is often preferred for a mutation directly associated with a framework-rendered application form.
Derive a robust request and response flow for a POST /api/orders endpoint that creates an order from a JSON request body.
A robust flow can be derived in the following sequence:
- Receive the request: Confirm that the method and route are correct.
- Check content type: Require an appropriate JSON content type and parse the body safely.
- Authenticate: Identify the current user from a trusted session or token.
- Validate structure: Verify that required fields such as item identifiers and quantities exist and have valid types.
- Validate business rules: Confirm that products exist, quantities are positive, inventory is available, and prices are obtained from trusted server data rather than the client.
- Calculate totals: Compute prices, discounts, taxes, and shipping on the server.
- Use a transaction: Create the order and update inventory atomically to prevent inconsistent state.
- Return the result: Respond with
201 Createdand the order representation, or return a meaningful4xxerror for invalid input or conflicts. - Handle unexpected failures: Log internal details securely and return a generic
500 Internal Server Errorresponse.
The endpoint should also use idempotency support for payment-related or retry-prone requests so that a repeated submission does not create duplicate orders.
What is an optimistic UI update? Explain its sequence of operations and contrast it with a pessimistic update.
An optimistic UI update changes the interface immediately, assuming that the server mutation will succeed. The request is sent in the background while the user sees the expected result without waiting for the response.
Typical sequence:
- Capture the current UI state.
- Apply the expected change locally.
- Mark the relevant item as pending if necessary.
- Send the mutation to the server.
- Confirm or reconcile the state when the response arrives.
- Roll back to the captured state if the mutation fails.
A pessimistic update waits for a successful server response before changing the visible state. Optimistic updates feel faster and work well for low-risk operations such as toggling a preference, but they require careful rollback, conflict handling, and pending-state design. Pessimistic updates are safer when failures are common or the server response can substantially differ from the client's prediction.
Describe how to implement rollback and error recovery for an optimistic update that modifies a task's completion status.
A reliable optimistic toggle can use the following approach:
- Store the task's previous completion state before changing it.
- Immediately update the interface to show the new state.
- Disable repeated toggles or associate the request with a version while it is pending.
- Send the mutation containing the task ID and intended state.
- If the server succeeds, replace the local item with the authoritative response.
- If the server fails, restore the previous state and display an accessible error message.
- If the server reports a conflict, fetch the current task and reconcile the UI with the authoritative value.
- Ensure that a failed request does not leave stale loading indicators or duplicate notifications.
For concurrent updates, the client may use request identifiers, timestamps, or server versions so that an older response cannot overwrite a newer local decision. The server should also authorize the task update independently of the optimistic client behavior.
Define a route handler in a modern web application framework. Explain its purpose and describe the main steps involved in creating one.
A route handler is a server-side function that receives an HTTP request for a particular URL and returns an HTTP response.
Purpose:
- It connects a URL and HTTP method to server-side application logic.
- It can read request data, access databases or external services, validate input, and return structured responses.
- It is commonly used to implement APIs and backend functionality.
Main steps:
- Create a file in the framework's API or route directory.
- Export functions corresponding to HTTP methods such as
GET,POST,PUT,PATCH, orDELETE. - Read parameters, query strings, headers, or request bodies.
- Perform validation and business logic.
- Return a response with appropriate data, status codes, and headers.
For example, a GET handler may retrieve records from a database and return them as JSON, while a POST handler may validate and store a newly submitted record.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →