Hands-On RESTful Web Services with TypeScript 3

1 (1 reviews total)
By Biharck Muniz Araújo
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to RESTful API Development

About this book

In the world of web development, leveraging data is the key to developing comprehensive applications, and RESTful APIs help you to achieve this systematically. This book will guide you in designing and developing web services with the power of TypeScript 3 and Node.js. You'll design REST APIs using best practices for request handling, validation, authentication, and authorization. You'll also understand how to enhance the capabilities of your APIs with ODMs, databases, models and views, as well as asynchronous callbacks. This book will guide you in securing your environment by testing your services and initiating test automation with different testing approaches. Furthermore, you'll get to grips with developing secure, testable, and more efficient code, and be able to scale and deploy TypeScript 3 and Node.js-powered RESTful APIs on cloud platforms such as the Google Cloud Platform. Finally, the book will help you explore microservices and give you an overview of what GraphQL can allow you to do.

By the end of this book, you will be able to use RESTful web services to create your APIs for mobile and web apps and other platforms.

Publication date:
March 2019
Publisher
Packt
Pages
470
ISBN
9781789956276

 

Chapter 1. Introduction to RESTful API Development

In order to get the best from any technology, it is necessary to understand deeply what the technology does. Throughout this chapter, RESTful concepts will be explained in detail with necessary elements to help you to develop and run RESTful services. The main objective of the chapter is to show you comprehensive examples that transpose these concepts to real-world scenarios and help you to understand their definitions in an easier way.

Currently, there is a huge necessity for applications to scale when necessary; they need to be fast, secure, portable, and trustable. These applications no longer serve one specific purpose; in fact, they work to solve corporative issues and meet the needs of end users.

APIs are the core elements for creating web and mobile applications. They provide structured data for your applications. This chapter mainly focuses on the definition of Representational State Transfer (REST) and RESTful principles, and describes the primary logic behind these architectural principles as well as the standards to follow while creating a web service.

The following topics will be covered in this chapter:

  • The REST definition
  • RESTful styles
  • The general concepts regarding REST 
  • HTTP methods and verbs
 

Technical requirements


There are no requirements for this chapter; this chapter will lay the foundation for what this book is going to cover.

 

What is REST?


RESTful web services are services built according to REST principles. The idea is to have them designed to essentially work well on the web. Alright, but what is REST? Let's start from the beginning, that is, by defining REST.

The REST style is a set of software engineering practices that contains constraints that should be used in order to create web services in distributed hypermedia systems. REST is not a tool and neither is it a language; in fact, REST is agnostic of protocols, components, and languages. 

It is important to say that REST is an architectural style and not a toolkit. REST provides a set of design rules in order to create stateless services that are shown as resources and, in some cases, sources of specific information such as data and functionality. The identification of each resource is performed by its unique Uniform Resource Identifier (URI). REST describes simple interfaces that transmit data over a standardized interface such as HTTP and HTTPS without any additional messaging layer, such as Simple Object Access Protocol (SOAP).

The consumer will access REST resources via a URIusing HTTP methods (this will be explained in more detail later). After the request, it is expected that a representation of the requested resource is returned. The representation of any resource is, in general, a document that reflects the current or intended state of the requested resource.

 

REST architectural styles


The REST architectural style describes six constraints. These constraints were originally described by Roy Fielding in his Ph.D. thesis ( https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm). They include the following:

  • Uniform interface
  • Stateless
  • Cacheable
  • Client-server architecture
  • A layered system
  • Code on demand (optional)

We will discuss them all minutely in the following subsections.

Uniform interface

Uniform interface is a constraint that describes a contract between clients and servers. One of the reasons to create an interface between them is to allow each part to evolve regardless of each other. Once there is a contract aligned with the client and server parts, they can start their works independently because, at the end of the day, the way that they will communicate is firmly based on the interface:

The uniform interface is divided into four main groups, calledprinciples:

  • Resource-based
  • The manipulation of resources using representations
  • Self-descriptive messages
  • Hypermedia as the Engine of Application State (HATEOAS)

Let's talk more about them.

Resource-based

One of the key things when a resource is being modeled is the URI definition. The URI is what defines a resource as unique. This representation is what will be returned for clients. If you decided to perform GET to the offer URI, the resource that returns should be a resource representing an order containing the ID order, creation date, and so on. The representation should be in JSON or XML.

Here is a JSON example:

{
    id : 1234,
    creation-date : "1937-01-01T12:00:27.87+00:20",
    any-other-json-fields...
}

Here is an XML example:

<order>
    <id>1234</id>
    <creation-date>1937-01-01T12:00:27.87+00:20</creation-date>
    any-other-xml-fields
</order>

The manipulation of resources using representations

Following the happy path, when the client makes a request to the server, the server responds with a resource that represents the current state of its resource. This resource can be manipulated by the client. The client can request what kind it desires for the representation such as JSON, XML, or plain text.

When the client needs to specify the representation, the HTTP Accept header is used.

Here you can see an example in plain text:

GET https://<HOST>/orders/12345
Accept: text/plain

The next one is in JSON format:

GET https://<HOST>/orders/12345
Accept: application/json

Self-descriptive messages

In general, the information provided by the RESTful service contains all the information about the resource that the client should be aware of. There is also a possibility of including more information than the resource itself. This information can be included as a link. In HTTP, it is used as the content-type header and the agreement needs to be bilateral—that is, the requestor needs to state the media type that it's waiting for and the receiver must agree about what the media type refers to.

Some examples of media types are listed in the following table:

Extension

Document Type

MIME type

.aac

AAC audio file

audio/aac

.arc

Archive document

application/octet-stream

.avi

Audio Video Interleave (AVI)

video/x-msvideo

.css

Cascading Style Sheets (CSS)

text/css

.csv

Comma-separated values (CSV)

text/csv

.doc

Microsoft Word

application/msword

.epub

Electronic publication (EPUB)

application/epub+zip

.gif

Graphics Interchange Format (GIF)

image/gif

.html

HyperText Markup Language (HTML)

text/html

.ico

Icon format

image/x-icon

.ics

iCalendar format

text/calendar

.jar

Java Archive (JAR)

application/java-archive

.jpeg

JPEG images

image/jpeg

.js

JavaScript (ECMAScript)

application/javascript

.json

JSON format

application/json

.mpeg

MPEG video

video/mpeg

.mpkg

Apple Installer Package

application/vnd.apple.installer+xml

.odt

OpenDocument text document

application/vnd.oasis.opendocument.text

.oga

OGG audio

audio/ogg

.ogv

OGG video

video/ogg

.ogx

OGG

application/ogg

.otf

OpenType font

font/otf

.png

Portable Network Graphics

image/png

.pdf

Adobe Portable Document Format (PDF)

application/pdf

.ppt

Microsoft PowerPoint

application/vnd.ms-powerpoint

.rar

RAR archive

application/x-rar-compressed

.rtf

Rich Text Format (RTF)

application/rtf

.sh

Bourne shell script

application/x-sh

.svg

Scalable Vector Graphics (SVG)

image/svg+xml

.tar

Tape Archive (TAR)

application/x-tar

.ts

TypeScript file

application/typescript

.ttf

TrueType Font

font/ttf

.vsd

Microsoft Visio

application/vnd.visio

.wav

Waveform Audio Format

audio/x-wav

.zip

ZIP archive

application/zip

.7z

7-zip archive

application/x-7z-compressed

 

There is also a possibility of creating custom media types. A complete list can be found at https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types.

HATEOAS

HATEOAS is a way that the client can interact with the response by navigating within it through the hierarchy in order to get complementary information.

For example, here the client makes a GET call to the order URI :

GET https://<HOST>/orders/1234

The response comes with a navigation link to the items within the 1234 order, as in the following code block:

{
    id : 1234,
    any-other-json-fields...,
    links": [
        {
            "href": "1234/items",
            "rel": "items",
            "type" : "GET"
        }
    ]
}

What happens here is that the link fields allow the client to navigate until 1234/items in order to see all the items that belong to the 1234 order.

Stateless

Essentially, stateless means that the necessary state during the request is contained within the request and it is not persisted in any hypothesis that could be recovered further. Basically, the URI is the unique identifier to the destination and the body contains the state or changeable state, or the resource. In other words, after the server handles the request, the state could change and it will send back to the requestor with the appropriate HTTP status code:

In comparison to the default session scope found in a lot of existing systems, the REST client must be the one that is responsible in providing all necessary information to the server, considering that the server should be idempotent.

Stateless allows high scalability since the server will not maintain sessions. Another interesting point to note is that the load balancer does not care about sessions at all in stateless systems.

In other words, the client needs to always pass the whole request in order to get the resource because the server is not allowed to hold any previous request state.

Cacheable

The aim of caching is to never have to generate the same response more than once. The key benefits of using this strategy are an increase in speed and a reduction in server processing.

Essentially, the request flows through a cache or a series of caches, such as local caching, proxy caching, or reverse proxy caching, in front of the service hosting the resource. If any of them match with any criteria during the request (for example, the timestamp or client ID), the data is returned based on the cache layer, and if the caches cannot satisfy the request, the request goes to the server:

Client-server architecture

The REST style separates clients from a server. In short, whenever it is necessary to replace either the server or client side, things should flow naturally since there is no coupling between them. The client side should not care about data storage and the server side should not care about the interface at all:

A layered system

Each layer must work independently and interact only with the layers directly connected to it. This strategy allows passing the request without bypassing other layers. For instance, when scaling a service is desired, you might use a proxy working as a load balancer—that way, the incoming requests are deliverable to the appropriate server instance. That being the case, the client side does not need to understand how the server is going to work; it just makes requests to the same URI.

The cache is another example that behaves in another layer, and the client does not need to understand how it works either:

Code on demand

In summary, this optional pattern allows the client to download and execute code from the server on the client side. The constraint says that this strategy improves scalability since the code can execute independently of the server on the client side:

 

HTTP methods for RESTful services


The use of HTTP verbs allows a clear understanding of what an operation is going to do. In general, the primary or most commonly used HTTP verbs are POST, GET, PUT, PATCH, and DELETE, which stand for create, read, update (PATCH and PUT), and delete, respectively. Of course, there are also a lot of other verbs, but they are not used as frequently:

Method

HTTP method description

GET

GET is the most common HTTP verb. Its function is to retrieve data from a server at the specified resource.

For example, a request made to the GET https://<HOST>/customers endpoint will retrieve all customers in a list format (if there is no pagination).

There is also the possibility of retrieving a specific customer such as GET https://<HOST>/customers/1234; in this instance, only the customer with the 1234 ID will be retrieved.

It is important to add that the GET request only retrieves data and does not modify any resources; it's considered a safe and idempotent method.

HEAD

The HEAD method does exactly what GET does, except that the server replies without the body.

POST

The most common usage of POST methods is to create a new resource.

PATCH

The PATCH method is used to apply partial modifications to a resource, such as updating a name or a date, but not the whole resource.

PUT

Different from the PATCH method, the PUT method replaces all of the resource.

DELETE

The DELETE method removes a resource.

CONNECT

The CONNECT method converts the connection request to a transparent TCP/IP tunnel, generally to facilitate encrypted communication with SSL (HTTPS) through an unencrypted HTTP proxy.

OPTIONS

The OPTIONS method returns the HTTP methods supported by the server for the specified URL.

TRACE

The TRACE method returns the same request that is sent to see whether there were changes and/or additions made by intermediate servers.

In order to explain these methods in detail, let's consider a simple entity called Customer. We will imagine that there is an API called Customers available through HTTP and its destination is a NoSQL database like in the following diagram:

                              

Considering that the database is empty, what should happen if we call the GET method by pointing to GET /CUSTOMERS? If you think that it should retrieve nothing, then you are absolutely right! Here is a request example:

GET https://<HOST>/customers

And here is the response:

[]

So, considering that there is no customer yet, let's create one using the POST method:

Request endpoint

Sample Request

Status code response

POST /customers
{
    "first_name":"John",
    "last_name":"Doe"
 }

HTTP status code 201

 

Considering the POST method is successful, the HTTP status code should be 201 (we will talk more about status codes in Chapter 2, Principles of Designing RESTful APIs) and calling the GET method now; the response should be similar to the following code block (we're considering that there is just one single consumer of this endpoint and we are that consumer, so we can guarantee the data behavior into the server):

Request endpoint

Sample Request

Status code response

GET /customers
[
  {
    "id" : 1,
    "first_name":"John",
    "last_name":"Doe"
  }
]

The HTTP status code is 200.

What if we add two more customers and call the GET method again? Take a look at the following code block:

Request endpoint

Sample Response

Status code response

GET /customers
[
  {
    "id" : 1,
    "first_name" : "John",
    "last_name" : "Doe"
  },
  {
    "id" : 2,
    "first_name" : "Mary",
    "last_name" : "Jane"
  },
  {
    "id" : 3,
    "first_name" : "Jane",
    "last_name" : "Doe"
  }
]

The HTTP status code is 200.

 

Nice, so if we call the GET method for a specific ID, the response should be like the following:

Request endpoint

Sample Response

Status code response

GET /customers/1
{
  "id" : 1,
  "first_name":"John",
  "last_name":"Doe"
}

The HTTP status code is 200.

 

We can also call POST methods for parent resources, such as /customers/1/orders, which will create new resources under the customer with ID 1. The same applies to the GET method, but only to retrieve the data as mentioned previously.

Note

Remember that the GET method should never modify any resource.

Okay, now that we know how to create and retrieve the resources, what if we want to change any information, such as the last name for John Doe? This one is easy—we just have to call the PATCH method in the same way that we called the POST method:

Request endpoint

Sample Request

Status code response

PATCH /customers/1
{
  "last_name" : "Doe Jr."
}

The HTTP status code is 204.

 

We can also change the information in a parent using a path as follows:

Request endpoint

Sample Request

Status code response

PATCH /customers/1/orders
{
  "status" : "closed" 
}

The HTTP status code 204.

 

And what if we need to change the whole resource? In that case, we should use thePUTmethod:

Request endpoint

Sample Request

Status code response

PUT /customers/1
{
  "first_name" : "Wolfgang",
  "last_name" : "Amadeus Mozart"
}

The HTTP status code is 201.

 

Instead of PATCH, you can use the PUT method. To do so, all the parameters are required to be passed as the body into the request, even those parameters that haven't changed.

Finally, if you want to remove a resource, use the DELETE method:

Request endpoint

Status code response

PUT /customers/1

The HTTP status code is 204.

 

Summary


In this chapter, we talked about the various  HTTP methods and when each one of them should be used. We also discussed the principles of RESTful services. All elements presented in this chapter and the upcoming chapters will be applied in the case study.

We also covered the general idea of HTTP methods and verbs based on examples with JSON. The REST architectural style was described based on six constraints.

In the next chapter, we will present the best practices related to RESTful design such as API endpoint organization, different ways to expose an API service, how to handle large datasets, naming conventions, the HTTP status codes, and API versioning.

 

Questions


  1. What method should be used in order to change the resource state?
  2. What is the best way to create a new resource?
  3. What are the REST architectural style constraints?
  4. What is the only optional REST architectural style constraint?
  5. If you need to change only two fields in a resource that contains more than two fields, what verb should you use?
  6. What is the verb used to update the whole resource?
  7. What does GET do?
 

Further reading


In order to improve your knowledge of REST, RESTful, and RESTful styles, the following books are recommended to be read, as they will be helpful in the coming chapters:

About the Author

  • Biharck Muniz Araújo

    Biharck Muniz Araújo is passionate about technology and academic research. He has been working as a software architect and lead programmer for the past 12 years. With over 16years' experience, he has been working with technology in relation to large-scale problems associated with web projects that demanded high-security standards for information transmission in companies in a variety of sectors, including telecoms, health, and finance. His background is in computer science, and he has a Master's degree in Electrical Engineering and a Ph.D. in Bioinformatics. Currently, he is focused on performance and algorithm design.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Really bad experience, the site is very unstable, I had to make several attempts to finally being able to pay, always getting errors from the back end. I couldn't pay for 3 days, using two different credit cards, I could complete the purchase at the 4th day. Additionally, there is no support at all in this cases, the form for it, had errors too when I tried to send (It never worked anyway). Very bad experience, very unstable site, I hope I don't need to purchase in this site again.

Recommended For You

Book Title
Unlock this full book FREE 10 day trial
Start Free Trial