Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if API is alive, should it be Get or Post method? [closed]

I am kind of new to API world. I need to check if service is alive at client side before calling any service method. It can be done at client side by passing API URL and getting the request status back. But for some other reasons, I need to add a dummy method in my API which will just return the status code. So from my client side, I will just call http://example.com/alive to check service status.

1) Do I need to have a Get or Post method? I won't be passing any parameters. 2) Is it okay to return just string or better have the method with return type httpresponsemessage?

 public string GetStatus()
    {
        //validate ip address

        return HttpStatusCode.OK.ToString();
    }
like image 937
user1263981 Avatar asked Jun 21 '18 16:06

user1263981


2 Answers

What about using HEAD. if you need to send some data from the client in a certain interval for the server to know whether the client is alive or not then, you can use POST something like /heartbeat or /sample etc. But if you only want to check the health status of the server. You can use Head also.

As per: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

EDITED You can also use GET if you don't want to return an empty result, then, in that case, you can return current datetime instead.

[RoutePrefix("ping")]
public class PingController: ApiController {

 [HttpGet]
 [Route("")]
 public IHttpActionResult Get() {
   return Ok(DateTime.UtcNow)
 }

}
like image 170
Ravi Pandey Avatar answered Oct 17 '22 05:10

Ravi Pandey


1) Do i need to have a Get or Post method? I won't be passing any parameters.

Feel free to use any of them, it doesn't matter, really.

2) Is it okay to return just string or better have the method with return type httprequestmessage?

Don't do it, please. It would be better to return HttpStatus 200 (OK).

public IHttpActionResult Ping()
{
    return Ok();
}
like image 22
Plastiquewind Avatar answered Oct 17 '22 06:10

Plastiquewind