2

I am trying to make an API that will Get a list of people depending on what you search by - PhoneNumber, Email, Name

My issue is I am not sure how to Route the API to do something like this...

[HttpGet, Route("SearchBy/{**searchByType**}/people")]
[NoNullArguments]
[Filterable]
public IHttpActionResult FindPeople([FromUri] string searchByType, object queryValue)
{
    var response = new List<SearchSummary>();
    switch (searchByType)
    {
        case "PhoneNumber":
            response = peopleFinder.FindPeople((PhoneNumber)queryValue);
            break;
        case "Email":
            response = peopleFinder.FindPeople((Email)queryValue);
            break;
        case "Name":
            response = peopleFinder.FindPeople((Name) queryValue);
            break;
    }
    return Ok(response);
}

Do I create a SearchBy object and pass in a member from that or maybe use an enum or constant somehow?

1 Answer 1

1

I would advise change things up a bit. First you can change the route template to be a little more RESTful. Next your under-lying data source could be a little more specific with the search.

//Matches GET ~/people/phone/123456789
//Matches GET ~/people/email/[email protected]
//Matches GET ~/people/name/John Doe  
[HttpGet, Route("people/{searchByType:regex(^phone|email|name$)}/{filter}")]
[NoNullArguments]
[Filterable]
public IHttpActionResult FindPeople(string searchByType, string filter) {
    var response = new List<SearchSummary>();
    switch (searchByType.ToLower()) {
        case "phone":
            response = peopleFinder.FindPeopleByPhone(filter);
            break;
        case "email":
            response = peopleFinder.FindPeopleByEmail(filter);
            break;
        case "name":
            response = peopleFinder.FindPeopleByName(filter);
            break;
        default:
            return BadRequest();
    }
    return Ok(response);
}

Reference: Attribute Routing in ASP.NET Web API 2

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.