Search Sreeni's Insights

Filter by content type
technical April 2, 2015 6 min read

What is RESTful API - resources, verbs and status codes?

RESTful API design explained through resources, HTTP verbs, safety, idempotence, Web API 2 controllers, and status codes using a news article example.

Share:

What is RESTful API - resources, verbs and status codes?

An Application Programming Interface (API) is not healthy only because it returns JSON. Consumers need a predictable way to identify resources, perform actions and understand the result. If one endpoint is using GET to change data and another is returning 200 for every failure, each client must learn a private rule and the API becomes difficult to evolve.

Representational State Transfer (REST) gives us a set of constraints for designing web APIs around resources. In this article, we are going to see resources, HTTP verbs, safety, idempotence and status codes, using a news article API as a worked example.

TL;DR Summary

  • A RESTful API models business resources and their representations.
  • Use nouns for resource paths and HTTP verbs for the operation.
  • Safe means an operation does not change server state as its intended effect.
  • Idempotent means repeating an operation has the same final effect as doing it once.
  • Status codes communicate the result, but the response body should add useful details.
  • Design from the consumer’s need and keep the contract consistent.

Challenges

Action-shaped endpoints

An endpoint such as /publishArticle may be understandable, but it mixes the business action and transport shape. Different teams may create /publish, /articlePublish and /setArticleStatus. A resource-oriented contract gives consumers a smaller vocabulary.

Ambiguous verbs

If a GET request publishes a news article, a browser prefetch or monitoring probe can change business state. This is a serious blind spot. Safe verbs should be safe to repeat and inspect, while state-changing operations should be explicit.

Meaningless status codes

Returning 200 with { "error": true } forces every consumer to inspect the body before knowing whether the request succeeded. A proper HTTP status allows common clients, monitoring and gateways to reason consistently.

What is a RESTful API?

A RESTful API is an HTTP interface which represents resources and applies REST constraints such as a uniform interface, stateless requests and representations of resource state.

In simple terms, a news article is a resource identified by /articles/42. GET reads it, PUT replaces it, PATCH changes part of it, and DELETE removes it. The API does not need to expose its database table name to make this contract useful.

Why REST is important?

REST uses HTTP concepts already understood by clients, proxies and monitoring tools. This reduces custom integration knowledge and creates a common front door. It is not a rule that every domain action must be forced into CRUD, but resource operations should be the default where they fit.

The following diagram depicts a client interacting with an article resource,

RESTful API resource and HTTP verb flow
RESTful API resource and HTTP verb flow

HTTP verbs, safety and idempotence

VerbActionIs Safe?Is Idempotent?
GETRead a representationYesYes
HEADRead headers onlyYesYes
POSTCreate or process a subordinate operationNoNo
PUTReplace a resource at a known URINoYes
PATCHPartially update a resourceNoNo (depends on implementation)
DELETERemove a resourceNoYes

Safety and idempotence are different. A safe request does not intend to change state. An idempotent request may change state once, but repeating it reaches the same final state.

Idempotence comes from mathematics: f(f(x)) = f(x). If we delete an article, it is gone. If we send DELETE again, it is still gone, although the second response may be 404. For a PUT, sending the same complete article representation twice should leave the article in the same state.

POST is commonly non-idempotent. Posting the same article twice may create two articles. If the business needs retry safety, use an idempotency key or design the operation around a known resource identifier.

Resource naming and representations

Use plural nouns for collections and identifiers for members,

GET    /api/articles
GET    /api/articles/42
POST   /api/articles
PUT    /api/articles/42
PATCH  /api/articles/42
DELETE /api/articles/42

The resource representation can include links, state and metadata. Keep the representation stable enough for consumers and version the contract when a breaking change is unavoidable. Filtering and paging should be explicit, for example GET /api/articles?topic=markets&page=2.

Web API 2 controller example

Find below a controller which is showing the normal status code decisions,

[RoutePrefix("api/articles")]
public class ArticlesController : ApiController
{
    [HttpGet]
    [Route("{id:int}", Name = "GetArticle")]
    public IHttpActionResult Get(int id)
    {
        Article article = repository.Find(id);
        if (article == null)
            return NotFound();
        return Ok(article);
    }

    [HttpPost]
    [Route("")]
    public IHttpActionResult Post(CreateArticleRequest request)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        Article article = service.Create(request);
        return CreatedAtRoute(
            "GetArticle",
            new { id = article.Id },
            article);
    }

    [HttpDelete]
    [Route("{id:int}")]
    public IHttpActionResult Delete(int id)
    {
        if (!service.Delete(id))
            return NotFound();
        return StatusCode(HttpStatusCode.NoContent);
    }

    [HttpPost]
    [Route("{id:int}/publish")]
    public IHttpActionResult Publish(int id)
    {
        if (!service.CanPublish(id))
            return Conflict();
        service.Publish(id);
        return StatusCode(HttpStatusCode.NoContent);
    }
}

CreatedAtRoute is returning 201 Created with a location to the new resource. NotFound is telling the consumer that the identifier is not present, NoContent is confirming a successful delete, and Conflict is showing that the requested state transition is not valid. The exact business rule is belonging to the service, not to the controller.

Status codes

Use status codes consistently,

  • 200 OK when a read or update returns a representation.
  • 201 Created when a resource is successfully created, with a Location header where practical.
  • 202 Accepted when work is queued and not completed yet.
  • 204 No Content when the operation succeeds without a response body.
  • 400 Bad Request when the input is invalid.
  • 401 Unauthorized when authentication is missing or invalid.
  • 403 Forbidden when the caller is authenticated but not allowed.
  • 404 Not Found when the resource does not exist.
  • 409 Conflict when the request conflicts with current resource state.
  • 500 Internal Server Error for an unexpected server failure, without the stack trace.

The status code is not enough for a validation error. Return a stable error shape with field details, but do not expose internal database or stack information. This lets the consumer fix a request while operations can investigate the server log.

Must Do and Don’ts

  • Must Do: Use nouns for resource paths and HTTP verbs for the normal action.
  • Must Do: Make GET safe, because monitoring and browser prefetch can call it.
  • Must Do: Test retries for PUT, DELETE and any idempotency-key based POST.
  • Don’t: use GET for publish, delete or another state-changing operation.
  • Don’t: return 200 for every business failure, otherwise clients are needing to inspect every body.
  • Be mindful: A 404 on the second DELETE can still be consistent with an idempotent operation, because the resource is remaining deleted.

If the API has no consistent verbs or status codes, support teams are reacting to every consumer error and clients are learning private rules. A proactive API contract uses the table, examples and tests before consumers are integrating. The trade-off is keeping the contract stable, hence in our case we prefer a small consistent resource model instead of exposing every internal business action.

How should we design?

Start with the resources and important state transitions. For an article, publishing may be a state change which uses POST /api/articles/42/publishing when it cannot be represented clearly as a normal update. It is better to use an explicit action than to make GET perform a hidden mutation.

Document the contract with Swagger and test safe and idempotent behaviour. The API should be stateless between requests, while authentication and resource state are carried explicitly. We will discuss documenting ASP.NET Web API with Swagger in an upcoming article.

Wrap up

In this article, we have looked at REST resources, HTTP verbs, safety, idempotence, Web API 2 controller code and status codes using a news article example. I appreciate your time and efforts to read this article. In the next article, I will walk you through whether we should start a new system with a monolith or microservices.

Related Posts