Let's move on to implementing the action method for getting a single question:
- Add the following skeleton method:
[HttpGet("{questionId}")]
public ActionResult<QuestionGetSingleResponse>
GetQuestion(int questionId)
{
// TODO - call the data repository to get the question
// TODO - return HTTP status code 404 if the question isn't
found
// TODO - return question in response with status code 200
}
Note the HttpGet attribute parameter.
In this method, the questionId parameter will be set to whatever comes after the controller root path. So, for the api/questions/3 path, questionId would be set to 3.
Notice that the return type is ActionResult<QuestionGetSingleResponse> rather than just QuestionGetSingleResponse. This is because our action method won't return QuestionGetSingleResponse in all the return paths—there will be a path that will return NotFoundResult when the question can't be found. ActionResult gives us the flexibility to return these different types.
- Let's call into the repository to get the question:
[HttpGet("{questionId}")]
public ActionResult<QuestionGetSingleResponse>
GetQuestion(int questionId)
{
var question = _dataRepository.GetQuestion(questionId);
// TODO - return HTTP status code 404 if the question isn't
found
// TODO - return question in response with status code 200
}
- Next, we can check whether the question has been found and return HTTP status code 404 if it hasn't been found:
[HttpGet("{questionId}")]
public ActionResult<QuestionGetSingleResponse> GetQuestion(int questionId)
{
var question = _dataRepository.GetQuestion(questionId);
if (question == null)
{
return NotFound();
}
// TODO - return question in response with status code 200
}
If the question isn't found, the result from the repository call will be null. So, we check for null and return a call to the NotFound method in ControllerBase, which returns HTTP status code 404.
- The last implementation step is to return the question that has been found:
[HttpGet("{questionId}")]
public ActionResult<QuestionGetSingleResponse> GetQuestion(int questionId)
{
var question = _dataRepository.GetQuestion(questionId);
if (question == null)
{
return NotFound();
}
return question;
}
- Let's give this a try by running the app and requesting question 1:
The question is returned as expected.
- Let's try requesting a question that doesn't exist:
We can get confirmation that a 404 status code is returned by opening the Dev Tools by pressing F12 and looking at the Network panel to see when the request was made.
- Stop our app running so that we are ready to implement another action method.
We've implemented a range of action methods that handle GET requests. It's time to implement action methods for the other HTTP methods next.