Ben
Ben

Reputation: 1231

How to design RESTful API endpoint to get by different fields with different data types

I am wondering what is the best way of design RESTful API endpoint for searching by different fields.

For example I have a resource as

class Employee 
{
    public int Id {get;set;}
    public string Name {get;set;}
    public string MobilePhoneNumber {get;set;}
    public string Email {get;set;}
}

Now I would like to design a GET endpoint to search an employee by different fields. If frontend passes an id to the endpoint, then I search by Id.

How to design the endpoint to fulfill this requirement. Or shall I create three endpoints for each field?

Thank you

Upvotes: 2

Views: 1961

Answers (2)

Dherik
Dherik

Reputation: 19100

I will suggest two GET endpoints. The first return one single object and the last one return an array.

For find the resource by ID, I could suggest an endpoint to accept the id as a mandatory information, like:

GET /api/employees/123

Because you can return just one single resource from the ID information. If the ID does not exist, you can return a 404 (Not Found) HTTP code.

Response:

{
    "id": 123,
    "name": "John Lock",
    "mobilePhoneNumber": "13334564454",
    "email": "[email protected]"
}

For the other fields, you create another endpoint to return an array of resources passing the fields as optional parameters:

GET /api/employees?name=John&mobilePhoneNumber=333&email=dmail.com

Response:

[
    {
        "id": 123,
        "name": "John Lock",
        "mobilePhoneNumber": "13334564454",
        "email": "[email protected]"
    },
    {
        "id": 321,
        "name": "John Smith",
        "mobilePhoneNumber": "33367546566",
        "email": "[email protected]"
    }

]

Upvotes: 2

strickt01
strickt01

Reputation: 4048

No need to create three endpoints. Just have a GET search endpoint returning multiple employees:

GET /api/employees

Then allow for the search parameters to be passed via the querystring. e.g

GET /api/employees?name=Ben&[email protected]

For the ID you would normally expose another GET endpoint to get just the one employee with that ID rather than allowing a search for multiple employees with the ID:

GET /api/employees/{Id}

Upvotes: 1

Related Questions