Request Object
The Request object provides access to all HTTP request data.
Getting request data:
$request = $this->getRequest();
// URL parameters
$id = $request->getParam('id');
$page = $request->getParam('p', 1); // With default
// POST data
$postData = $request->getPostValue();
$title = $request->getPostValue('title');
// All parameters
$allParams = $request->getParams();
// HTTP method
$method = $request->getMethod(); // GET, POST, PUT, DELETE
// Request URI
$uri = $request->getRequestUri();
$pathInfo = $request->getPathInfo();
// Headers
$accept = $request->getHeader('Accept');
$contentType = $request->getHeader('Content-Type');
Request object methods:
// Route information
$routeName = $request->getRouteName();
$controllerName = $request->getControllerName();
$actionName = $request->getActionName();
// Set parameters (for forwarding)
$request->setParam('key', 'value');
$request->setRouteName('catalog');
$request->setControllerName('product');
$request->setActionName('view');
// Check request type
$isPost = $request->isPost();
$isGet = $request->isGet();
$isAjax = $request->isAjax();
JSON request body:
$jsonData = $request->getContent();
$data = json_decode($jsonData, true);
Response Object
The Response object controls the HTTP response sent to the client.
Setting response data:
$response = $this->getResponse();
// Set body
$response->setBody('Hello World');
$response->setBody(json_encode($data));
// Set headers
$response->setHeader('Content-Type', 'application/json');
$response->setHeader('X-Custom-Header', 'value');
// Remove header
$response->setHeader('X-Custom-Header', null, true);
// Set HTTP status code
$response->setStatusCode(200); // OK
$response->setStatusCode(404); // Not Found
$response->setStatusCode(500); // Server Error
Response for JSON API:
public function execute()
{
$data = ['status' => 'success', 'message' => 'Saved'];
$response = $this->getResponse();
$response->setHeader('Content-Type', 'application/json');
$response->setBody(json_encode($data));
return $response;
}
Response for file download:
public function execute()
{
$response = $this->getResponse();
$response->setHeader('Content-Type', 'text/csv');
$response->setHeader('Content-Disposition', 'attachment; filename="export.csv"');
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setBody($csvContent);
return $response;
}
Headers and Cookies
Managing HTTP headers and cookies in Magento.
HTTP headers:
// Set header
$this->getResponse()->setHeader('Content-Type', 'text/html');
// Set multiple headers
$this->getResponse()->setHeader('Cache-Control', 'no-cache, no-store');
$this->getResponse()->setHeader('Pragma', 'no-cache');
// Check if header exists
if ($this->getResponse()->canSetHeaders()) {
$this->getResponse()->setHeader('X-Frame-Options', 'SAMEORIGIN');
}
Cookies:
// Get cookie value
$value = $this->getRequest()->getCookieValue('cookie_name');
// Set cookie via CookieManager
$cookieManager = $this->_objectManager->get(
\Magento\Framework\Stdlib\Cookie\CookieManagerInterface::class
);
$cookieManager->setCookie(
'cookie_name',
'cookie_value',
[
'path' => '/',
'domain' => '.example.com',
'httponly' => true,
'secure' => true,
'lifetime' => 3600
]
);
// Delete cookie
$cookieManager->deleteCookie('cookie_name');
Session:
// Get session
$session = $this->_objectManager->get(
\Magento\Framework\Session\SessionManagerInterface::class
);
// Set session data
$session->setData('key', 'value');
// Get session data
$value = $session->getData('key');
// Clear session
$session->unsData('key');
HTTP Status Codes
Proper HTTP status codes for API and web responses.
Common status codes:
200 OK — Successful request
201 Created — Resource created
204 No Content — Successful, no response body
301 Moved Permanently — Permanent redirect
302 Found — Temporary redirect
400 Bad Request — Invalid input
401 Unauthorized — Authentication required
403 Forbidden — Permission denied
404 Not Found — Resource doesn't exist
405 Method Not Allowed — HTTP method not supported
422 Unprocessable Entity — Validation failed
500 Internal Server Error — Server error
503 Service Unavailable — Service down
Setting status codes:
// In controller
$this->getResponse()->setStatusCode(404);
$this->getResponse()->setBody(__('Page not found'));return $this->getResponse();
// JSON API response
public function execute()
{
try {
$result = $this->service->process();
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setHeader('Content-Type', 'application/json');
$response->setBody(json_encode($result));
return $response;
} catch (\Exception $e) {
$response = $this->getResponse();
$response->setStatusCode(500);
$response->setHeader('Content-Type', 'application/json');
$response->setBody(json_encode(['error' => $e->getMessage()]));
return $response;
}
}
REST API status codes:
// GET success: 200
// POST success: 201
// PUT success: 200
// DELETE success: 204
// Validation error: 422
// Not found: 404
// Unauthorized: 401
Quiz
1. How do you get POST data in a controller?
2. What HTTP status code indicates resource not found?
3. How do you set a response header?
4. What is the correct status code for resource creation?
Flashcards
Question
How do you get a URL parameter?
Click to reveal answer
Answer
$this->getRequest()->getParam('name')
Question
How do you set the HTTP status code?
Click to reveal answer
Answer
$this->getResponse()->setStatusCode(200)
Question
What status code means 'Not Found'?
Click to reveal answer
Answer
404
Question
How do you get a cookie value?
Click to reveal answer
Answer
$this->getRequest()->getCookieValue('name')
Question
What is the status code for created resources?
Click to reveal answer
Answer
201 Created
Revision Notes
Key Takeaways
- 1. Request object provides access to all HTTP request data
- 2. Response object controls HTTP headers and body
- 3. Cookies managed via CookieManagerInterface
- 4. Status codes: 200 OK, 201 Created, 404 Not Found, 500 Error
- 5. Always set Content-Type header for API responses
- 6. Use getRequest()->isAjax() to detect AJAX requests
Interview Tips
- • Explain how to access request parameters
- • Describe response header management
- • Know common HTTP status codes and when to use them
- • Discuss cookie and session handling
Cheat Sheet
Request/Response Cheat Sheet
Request:
$this->getRequest()->getParam('id')
$this->getRequest()->getPostValue()
$this->getRequest()->getMethod()
$this->getRequest()->isAjax()
Response:
$this->getResponse()->setBody($content)
$this->getResponse()->setHeader('Type', 'json')
$this->getResponse()->setStatusCode(200)
Status codes:
- 200: OK
- 201: Created
- 204: No Content
- 400: Bad Request
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 500: Server Error