The JS runtimes
Published in

The JS runtimes

Using HTTP status codes in Deno

Purpose

HTTP status codes are one of the most basic constants used in any web application. Official HTTP status codes range from 100–599. These status codes are useful in two scenarios:

  • As a server: For a web server, the response needs to be sent with an appropriate HTTP status code (most popular being 200 OK).
  • As a client: For an HTTP client, the response from the server would come with an HTTP status code.

In either of the cases, there is a need to read, write, or understand HTTP status codes. While the official HTTP status codes are fixed, it’s not elegant to directly use numbers like 206, 403, 412, 511, etc. These magic numbers could be readable for experts, but for most people, it’d require them to Google the code to understand the meaning.

Deno provides an elegant way to read, write, and understand HTTP status codes. All the official status codes are covered by Deno.

Functions and Constants

There are two ways to use the HTTP status codes in Deno.

  • Status code number
  • Status code description

The first way is to include the Status object from the HTTP status module. This status object contains key-value pairs where:

  • Key is the user-friendly name of the numeric status code
  • Value is the numeric status code
import { Status } from "https://deno.land/std/http/http_status.ts"Status.Continue
//100
Status.OK
//200

The second way is to use the STATUS_TEXT map to get a description of the status code from the numeric value.

import { Status, STATUS_TEXT } from "https://deno.land/std/http/http_status.ts"STATUS_TEXT.get(Status.UnsupportedMediaType);
//Output: Unsupported Media Type

Status Object

Here is the complete list of the user-friendly keys and numeric values present in the Status object:

Status.Continue= 100
Status.SwitchingProtocols= 101
Status.Processing= 102
Status.EarlyHints= 103
Status.OK= 200
Status.Created= 201
Status.Accepted= 202
Status.NonAuthoritativeInfo= 203
Status.NoContent= 204
Status.ResetContent= 205
Status.PartialContent= 206
Status.MultiStatus= 207
Status.AlreadyReported= 208
Status.IMUsed= 226
Status.MultipleChoices= 300
Status.MovedPermanently= 301
Status.Found= 302
Status.SeeOther= 303
Status.NotModified= 304
Status.UseProxy= 305
Status.TemporaryRedirect= 307
Status.PermanentRedirect= 308
Status.BadRequest= 400
Status.Unauthorized= 401
Status.PaymentRequired= 402
Status.Forbidden= 403
Status.NotFound= 404
Status.MethodNotAllowed= 405
Status.NotAcceptable= 406
Status.ProxyAuthRequired= 407
Status.RequestTimeout= 408
Status.Conflict= 409
Status.Gone= 410
Status.LengthRequired= 411
Status.PreconditionFailed= 412
Status.RequestEntityTooLarge= 413
Status.RequestURITooLong= 414
Status.UnsupportedMediaType= 415
Status.RequestedRangeNotSatisfiable= 416
Status.ExpectationFailed= 417
Status.Teapot= 418
Status.MisdirectedRequest= 421
Status.UnprocessableEntity= 422
Status.Locked= 423
Status.FailedDependency= 424
Status.TooEarly= 425
Status.UpgradeRequired= 426
Status.PreconditionRequired= 428
Status.TooManyRequests= 429
Status.RequestHeaderFieldsTooLarge= 431
Status.UnavailableForLegalReasons= 451
Status.InternalServerError= 500
Status.NotImplemented= 501
Status.BadGateway= 502
Status.ServiceUnavailable= 503
Status.GatewayTimeout= 504
Status.HTTPVersionNotSupported= 505
Status.VariantAlsoNegotiates= 506
Status.InsufficientStorage= 507
Status.LoopDetected= 508
Status.NotExtended= 510
Status.NetworkAuthenticationRequired= 511

STATUS_TEXT map

Here is the complete list of key values present in the STATUS_TEXT map:

Status.Continue=Continue
Status.SwitchingProtocols=Switching Protocols
Status.Processing=Processing
Status.EarlyHints=Early Hints
Status.OK=OK
Status.Created=Created
Status.Accepted=Accepted
Status.NonAuthoritativeInfo=Non-Authoritative Information
Status.NoContent=No Content
Status.ResetContent=Reset Content
Status.PartialContent=Partial Content
Status.MultiStatus=Multi-Status
Status.AlreadyReported=Already Reported
Status.IMUsed=IM Used
Status.MultipleChoices=Multiple Choices
Status.MovedPermanently=Moved Permanently
Status.Found=Found
Status.SeeOther=See Other
Status.NotModified=Not Modified
Status.UseProxy=Use Proxy
Status.TemporaryRedirect=Temporary Redirect
Status.PermanentRedirect=Permanent Redirect
Status.BadRequest=Bad Request
Status.Unauthorized=Unauthorized
Status.PaymentRequired=Payment Required
Status.Forbidden=Forbidden
Status.NotFound=Not Found
Status.MethodNotAllowed=Method Not Allowed
Status.NotAcceptable=Not Acceptable
Status.ProxyAuthRequired=Proxy Authentication Required
Status.RequestTimeout=Request Timeout
Status.Conflict=Conflict
Status.Gone=Gone
Status.LengthRequired=Length Required
Status.PreconditionFailed=Precondition Failed
Status.RequestEntityTooLarge=Request Entity Too Large
Status.RequestURITooLong=Request URI Too Long
Status.UnsupportedMediaType=Unsupported Media Type
Status.RequestedRangeNotSatisfiable=Requested Range Not Satisfiable
Status.ExpectationFailed=Expectation Failed
Status.Teapot=I'm a teapot
Status.MisdirectedRequest=Misdirected Request
Status.UnprocessableEntity=Unprocessable Entity
Status.Locked=Locked
Status.FailedDependency=Failed Dependency
Status.TooEarly=Too Early
Status.UpgradeRequired=Upgrade Required
Status.PreconditionRequired=Precondition Required
Status.TooManyRequests=Too Many Requests
Status.RequestHeaderFieldsTooLarge=Request Header Fields Too Large
Status.UnavailableForLegalReasons=Unavailable For Legal Reasons
Status.InternalServerError=Internal Server Error
Status.NotImplemented=Not Implemented
Status.BadGateway=Bad Gateway
Status.ServiceUnavailable=Service Unavailable
Status.GatewayTimeout=Gateway Timeout
Status.HTTPVersionNotSupported=HTTP Version Not Supported
Status.VariantAlsoNegotiates=Variant Also Negotiates
Status.InsufficientStorage=Insufficient Storage
Status.LoopDetected=Loop Detected
Status.NotExtended=Not Extended
Status.NetworkAuthenticationRequired=Network Authentication Required

Examples

Let’s go over some examples and see how the status codes would get used.

The first example is that sends status codes 200 and 400 from a simple web server:

import { Status } from "https://deno.land/std/http/http_status.ts"
import { serve } from "https://deno.land/std/http/server.ts";
const s = serve({ port: 3000 });
for await (const req of s) {
//do something
//if --- some parameters are missing
req.respond({ status: Status.BadRequest });
//do something more
req.respond({ status: Status.OK,
body: JSON.stringify({ body: "Hello World" }) });
}

If there are some parameters missing in the request, it sends Status.BadRequest (400). If everything is good, it sends Status.OK (200). The status text i.e. the description is sent automatically by Deno.

The second example is about getting the status text. As mentioned above, the status text is sent automatically by Deno. However, if the status text is required to be logged somewhere, use the STATUS_TEXT map to get the text:

import { Status, STATUS_TEXT } from "https://deno.land/std/http/http_status.ts"
import { serve } from "https://deno.land/std/http/server.ts";
const s = serve({ port: 3000 });
for await (const req of s) {
//do something
//if --- some parameters are missing
req.respond({ status: Status.BadRequest });
logger.debug('Response sent: ', Status.BadRequest, STATUS_TEXT.get(Status.BadRequest));
//Log: Response sent: 400 Bad Request
//do something more
req.respond({ status: Status.OK,
body: JSON.stringify({ body: "Hello World" }) });

logger.debug('Response sent: ', Status.OK, STATUS_TEXT.get(Status.OK));
//Log: Response sent: 200 OK
}

This story is a part of the exclusive medium publication on Deno: Deno World.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store