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 - or or

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

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, 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.

1public class PersonSearchModel
3    public string Firstname { get; set; }
4    public string Lastname { get; set; }
5    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 -

2public async Task<IActionResult> Search([FromBody]List<PersonSearchModel> people)
4	// Perform search
5	// snip..

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

Full source code available here.

comments powered by Disqus