Task Description:
In this exercise, you are required to create a simple Ruby on Rails API endpoint. This task is designed to assess your knowledge of Rails routing, controllers, and basic data handling.
Duration:
20 minutes
Objective:
Create a Rails API endpoint that performs the following operations:
- Endpoint Name:
/api/v1/messages
- HTTP Method:
POST
- Functionality:
- Accept a JSON request with two parameters:
username
(string) andmessage
(string). - Validates that both
username
andmessage
are present. If either is missing, the endpoint should return a 400 Bad Request status with a relevant error message. - If both parameters are present, the endpoint should return a 200 OK status with a JSON response that includes a timestamp and echoes back the received
username
andmessage
.
- Accept a JSON request with two parameters:
Expected JSON Request Format:
{
"username": "sampleUser",
"message": "Hello, Rails!"
}
Expected JSON Response Format:
On Success:
{
"timestamp": "2021-01-01T00:00:00Z",
"username": "sampleUser",
"message": "Hello, Rails!"
}
On Failure (e.g., missing parameters):
{
"error": "Missing required parameters"
}
Guidelines:
- Create a new controller named MessagesController.
- Define the POST route in config/routes.rb.
- Implement the logic in the create action of the controller.
- Ensure the response is in JSON format.
- Write clean, readable code and handle potential errors gracefully.
Evaluation Criteria:
- Correct implementation of the endpoint.
- Proper handling of HTTP methods and status codes.
- Code readability and structure.
- Handling of edge cases and errors.
Notes:
- You don't need to set up a database for this exercise. The focus is on routing, controller logic, and data handling.
- Use comments to explain your thought process if needed.