0

I'm creating api using ASP.NET Web API

I have a method in repository which adds worker to company. Here is the method:

public void AddToCompanyBy(Guid workerId, Guid companyId)
{
  var worker = GetById(workerId);
  var company = DbContext.Set<Company>().Find(companyId);

  if (worker == null)
    throw new Exception("This worker does not exist");
  if (company == null)
    throw new Exception("This company does not exist");

  company.Workers.Add(worker);
}

And I have an ApiController action that invokes this method. Here is this action:

public IHttpActionResult AddToCompany(Guid workerId, Guid companyId)
{
  try
  {
    UoW.Workers.AddToCompanyBy(workerId, companyId);
    return Ok();
  }
  catch (Exception ex)
  {
    return BadRequest();
  }
}

So my questions are: am I right returning response as OK or I have to choose another type for response? Should I also return entity? How do I have mark the action (PUT or PATCH or GET)?

ekad
  • 14,436
  • 26
  • 44
  • 46
Nurzhan Aitbayev
  • 797
  • 1
  • 10
  • 23

1 Answers1

1
  • am I right returnign response as OK or I have to choose another type for response

It is ok to return OK response. You shouldn't specify return type because of Content Negotiation in Web API.

  • Should I also return entity?

It depends on your API and what do consumers of your API expect to get as a result. If it is enough just to know that everything was correct you can leave just OK message. If they need some data that was generated by your server, for exmaple incremented ID, you should return this data or even full entity.

  • How do I have mark the action (PUT or PATCH or GET)?

    [HttpPost]
    public IHttpActionResult AddToCompany(Guid workerId, Guid companyId)

    [HttpGet]
    public IHttpActionResult AddToCompany(Guid workerId, Guid companyId)

UPDATED according to comment:

  • I mean which verb should I choose in this particular case?

Both PUT and POST can be used for creating. For sure you shouldn't use GET verb for creation or update.

General Http verbs specification: w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3

Post with this discussion: stackoverflow.com/questions/630453/put-vs-post-in-rest

Community
  • 1
  • 1
ntl
  • 1,289
  • 1
  • 10
  • 16
  • Sorry, I mean which verb should I choose in this particular case? – Nurzhan Aitbayev Aug 08 '14 at 10:50
  • 1
    General Http verbs specification: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3 Post with discussion: http://stackoverflow.com/questions/630453/put-vs-post-in-rest – ntl Aug 08 '14 at 10:54
  • Please, check my main comment for an answer. I added it there. – ntl Aug 08 '14 at 10:59