Practical Examples: Designing REST Endpoints
Learn how to start designing future APIs with REST endpoints and CRUD actions using Deno.
We'll cover the following...
Create an HTTP server with the standard library
Deno offers an http
module for HTTP client and server implementations among its standard libraries. Creating an HTTP server is very easy with this module and is possible with just a few lines of code.
The code widget below shows an HTTP server example using Deno’s standard library. The script listens to port 5400 and returns the string I am a DENO server 🦕
as a response when it receives a request.
import { serve } from "https://deno.land/std@0.125.0/http/server.ts"; import { Status } from "https://deno.land/std@0.125.0/http/http_status.ts"; const server_port = 5400; function req_handler(req: Request): Response { console.log("\nReceived a request..."); const body = JSON.stringify({ message: "I am a DENO server 🦕" }); return new Response(body, { status: Status.OK, // 200 headers: { "content-type": "application/json; charset=utf-8", }, }); } // Port is optional. Default port is 8000 serve(req_handler, { port: server_port}) console.log("Listening on PORT: ", server_port);
The utility script https://deno.land/std/http/http_status.ts
exposes a Status
enum that conveniently provides all the HTTP statuses for our project. These enum values are descriptive and much easier to read than the numeric code version:
export enum Status {OK = 200,/** RFC 7231, 6.3.2 */Created = 201,/** RFC 7231, 6.3.3 */Accepted = 202,/** RFC 7231, 6.3.4 */NonAuthoritativeInfo = 203,/** RFC 7231, 6.3.5 */NoContent = 204,/** RFC 7231, 6.5.1 */BadRequest = 400,/** RFC 7231, 6.6.1 */InternalServerError = 500,/** RFC 7231, 6.6.2 */NotImplemented = 501,/** RFC 7231, 6.6.3 */BadGateway = 502// ...
Deno’s core team put a lot of effort into ...