Using Other Verbs with Web API

Full source code available here.

You will often use the GET verb when making requests to an API. You have probably used it like this –

www.example.com/person/ or
www.example.com/person/1 or
www.example.com/person?firstname=dave&lastname=daniels&age=22

All very simple, but what if you wanted to to search for many people at the same time, and I don’t mean all the people aged 22, or all the people with the first name Dave.

What if you wanted to look for Dave, Tom, Steve and Dan in one request, or all the people aged 22, 33, or 44.

You could go down the road of adding them to the query string, something like

www.example.com/person?firstperson_firstname=dave&secondperson_firstname=tom&...

But this a bad idea.

This is where the HTTP SEARCH method comes in. If this doesn’t sound familiar, that might be because it is currently an IETF draft https://tools.ietf.org/html/draft-snell-search-method-00, but tools like Fiddler support it.

SEARCH differs from GET by having a body. In this body you can have any content you want. For our scenario we will use a json body with an array of things to search for. You have to specify in the header what the content type of the body, e.g. Content-Type: application/json, (just like you do with a POST or a PUT).

I’ve created a very simple POCO to represent the things I want to search by.

public class PersonSearchModel
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public int Age { get; set; }
}

Into the body of the SEARCH request I have a json array of PersonSearchModel.

[
  {
    "firstname": "Dave",
    "lastname": "Davis",
    "age": 22
  },
  {
    "firstname": "Larry",
    "lastname": "Landers"
  },
  {
    "firstname": "Steve",
    "lastname": "Smith",
    "age": 44
  }
]

Now we can search for as many people as we like in as complicated way as we like.

In the PersonController I have a Search method –

[AcceptVerbs("SEARCH")]
public async Task<IActionResult> Search([FromBody]List<PersonSearchModel> people)
{
	// Perform search
	// snip..
}

Inside the body of the method you can search in any manner you choose.
here.

Full source code available here.

2 thoughts on “Using Other Verbs with Web API

  1. So, is this the answer for GET not having a body? In a micro-service, we had provide multiple GET end points because we couldn’t provide filter object in a body.

Leave a Reply

Your email address will not be published. Required fields are marked *