简体   繁体   中英

WebApi: What is the difference between these 2 types of parameters

This is the first time that i'm seeing this ways of doing things in a web-api.

So let me put you in context:

I have a web api where we have two routes:

Method one:

[HttpGet]
[Route("message-activity")]
public PagedResult<AuditedMessage> GetMessageActivity(int page)
{
}

Method 2:

[HttpGet]
[Route("message-activity/{messageID}")]
public AuditedMessage GetMessage(string messageID)
{
}

My question is:

Talking about good practices in webApi's. -Is the first method acceptable? -Is it right? -Is that anything wrong with the second method?

Thanks!

Using first method, parameter will be specified using query string. ie : message-activity?page=paramValue

While Using second method, you can simply pass parameter in the API call URL ie : message-activity/paramValue

Both of the method will work equally

In light of your edited question: There might be something wrong, or it might not be. To elaborate: The second version just returns a single result, the first one returns a paged list of results. If I have an existing messageID and I am only interested in this message, the second one is the best. If I need to to show a list of messages, the first one is vastly better. On a normal CRUD Controller, I would expect both methods.

to be honest I don't like any of them.

why?

let's look at the first one:

GetMessageActivity(int page)
  • What message?
  • what does page mean?
  • what's the page size?

if you want it to make sense and paginate the results then perhaps it could look like this:

[HttpGet]
[Route("message-activity")]
public PagedResult<MessageActivity> GetMessageActivity(string messageID, int pageSize, int pageNumber)
{
}

of course you'd update the route to match that.

That would make more sense to me. you return this MessageActivity data, whatever that is, not a message. If you want to return a message then return a message like in the second method.

Second one is strange as well:

[HttpGet]
[Route("message-activity/{messageID}")]
public AuditedMessage GetMessage(string messageID)
{
}

Well, if you want to load a message than the route should be message, not message-activity.

Something like:

[HttpGet]
    [Route("message/{messageID}")]
    public AuditedMessage GetMessage(string messageID)
    {
    }

I would change both so they make sense. An API is written for clients and those clients need to understand very quickly what's going on.

You can't compare the two as they refer to different things. You want to work with a message then your route, params and outputs need to reflect that. If you want to work with this MessageActivity then let your endpoint reflect that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM