0% found this document useful (0 votes)
17 views42 pages

Rest

The POST method is commonly used to create new resources. It is often used to create subordinate resources related to a parent resource. Upon successful creation, the server returns HTTP status 201 (Created) along with a Location header pointing to the newly created resource.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views42 pages

Rest

The POST method is commonly used to create new resources. It is often used to create subordinate resources related to a parent resource. Upon successful creation, the server returns HTTP status 201 (Created) along with a Location header pointing to the newly created resource.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

REST

REST is an acronym
for REpresentational State Transfer and an
architectural style for distributed hypermedia
systems. Roy Fielding first presented it in 2000 in
his famous dissertation. Since then, it has become
one of the most widely used approaches for
building web-based APIs (Application
Programming Interfaces).
REST is not a protocol or a standard, it is an
architectural style. During the development phase,
API developers can implement REST in a variety
of ways.
Like the other architectural styles, REST also has
its guiding principles and constraints. These
principles must be satisfied if a service interface is
to be referred to as RESTful.
A Web API (or Web Service) conforming to the
REST architectural style is called a REST
API (or RESTful API).
The Six Guiding Principles of REST
REST is based on some constraints and principles
that promote simplicity, scalability, and
statelessness in the design. The six guiding
principles or constraints of the RESTful
architecture are:
1.1. Uniform Interface
By applying the principle of generality to the
components interface, we can simplify the overall
system architecture and improve the visibility of
interactions. Multiple architectural constraints help
in obtaining a uniform interface and guiding the
behavior of components.
The following four constraints can achieve a
uniform REST interface:
Identification of resources – The interface must
uniquely identify each resource involved in the
interaction between the client and the server.
Manipulation of resources through
representations – The resources should have
uniform representations in the server response.
API consumers should use these representations to
modify the resource state in the server.
Self-descriptive messages – Each resource
representation should carry enough information to
describe how to process the message. It should
also provide information on the additional actions
that the client can perform on the resource.
Hypermedia as the engine of application state –
The client should have only the initial URI of the
application. The client application should
dynamically drive all other resources and
interactions with the use of hyperlinks.
In simpler words, REST defines a consistent and
uniform interface for interactions between clients
and servers. For example, the HTTP-based REST
APIs make use of the standard HTTP methods
(GET, POST, PUT, DELETE, etc.) and the URIs
(Uniform Resource Identifiers) to identify
resources.
1.2. Client-Server
The client-server design pattern enforces
the separation of concerns, which helps the client
and the server components evolve independently.
By separating the user interface concerns (client)
from the data storage concerns (server), we
improve the portability of the user interface across
multiple platforms and improve scalability by
simplifying the server components.
While the client and the server evolve, we have to
make sure that the interface/contract between the
client and the server does not break.

1.3. Stateless
Statelessness mandates that each request from the
client to the server must contain all of the
information necessary to understand and complete
the request.
The server cannot take advantage of any
previously stored context information on the
server.
For this reason, the client application must entirely
keep the session state.

1.4. Cacheable
The cacheable constraint requires that a response
should implicitly or explicitly label itself as
cacheable or non-cacheable.
If the response is cacheable, the client application
gets the right to reuse the response data later for
equivalent requests and a specified period.

1.5. Layered System


The layered system style allows an architecture to
be composed of hierarchical layers by constraining
component behavior. In a layered system, each
component cannot see beyond the immediate layer
they are interacting with.
A layman’s example of a layered system is
the MVC pattern. The MVC pattern allows for a
clear separation of concerns, making it easier to
develop, maintain, and scale the application.

1.6. Code on Demand (Optional)


REST also allows client functionality to be
extended by downloading and executing code in
the form of applets or scripts.

What is a Resource?
The key abstraction of information in REST is
a resource. Any information that we can name can
be a resource. For example, a REST resource can
be a document or image, a temporal service, a
collection of other resources, or a non-virtual
object (e.g., a person).
The state of the resource at any particular time is
known as the resource representation. The
resource representations consist of:
the data
the metadata describing the data
and the hypermedia links that can help the clients
transition to the next desired state.
A REST API consists of an assembly of
interlinked resources. This set of resources is
known as the REST API’s resource model.
Resource Identifiers
REST uses resource identifiers to identify each
resource involved in the interactions between the
client and the server components.
2.2. Hypermedia
The data format of a representation is known as
a media type. The media type identifies a
specification that defines how a representation is
to be processed.
A RESTful API looks like hypertext. Every
addressable unit of information carries an address,
either explicitly (e.g., link and id attributes) or
implicitly (e.g., derived from the media type
definition and representation structure).
Self-Descriptive
Further, resource representations shall be self-
descriptive: the client does not need to know if a
resource is an employee or a device. It should act
based on the media type associated with the
resource.

Singleton and Collection Resources


A resource can be a singleton or a collection.
For example, “customers” is a collection resource
and “customer” is a singleton resource (in a
banking domain).
We can identify “customers” collection resource
using the URI “/customers“. We can identify a
single “customer” resource using the URI
“/customers/{customerId}“.
/customers //is a collection resource

/customers/{id} // is a singleton resource


1.2. Collection and Sub-collection Resources
A resource may contain sub-collection
resources also.
For example, sub-collection resource “accounts”
of a particular “customer” can be identified using
the URN “/customers/{customerId}/accounts” (in
a banking domain).
Similarly, a singleton resource “account” inside
the sub-collection resource “accounts” can be
identified as follows:
“/customers/{customerId}/accounts/{accountId}“.
/customers //is a collection
resource

/customers/{id}/accounts // is a sub-
collection resource
1.3. URI
REST APIs use Uniform Resource
Identifiers (URIs) to address resources. REST API
designers should create URIs that convey a REST
API’s resource model to the potential clients of the
API. When resources are named well, an API is
intuitive and easy to use. If done poorly, that same
API can be challenging to use and understand.
The constraint of a uniform interface is partially
addressed by the combination of URIs and HTTP
verbs and using them in line with the standards
and conventions.

REST Architectural Elements


The Representational State Transfer (REST) style
is an abstraction of the architectural elements
within a distributed hypermedia system. REST
ignores the details of component implementation
and protocol syntax in order to focus on the roles
of components, the constraints upon their
interaction with other components, and their
interpretation of significant data elements. It
encompasses the fundamental constraints upon
components, connectors, and data that define the
basis of the Web architecture, and thus the essence
of its behavior as a network-based application.
Data Elements
Table 5-1: REST Data Elements
Data Element Modern Web Examples
the intended conceptual target
resource
of a hypertext reference
resource identifier URL, URN
representation HTML document, JPEG image
representation
media type, last-modified time
metadata
resource metadata source link, alternates, vary
if-modified-since, cache-
control data
control
Resources and Resource Identifiers
The key abstraction of information in REST is
a resource. Any information that can be named
can be a resource: a document or image, a
temporal service (e.g. "today's weather in Los
Angeles"), a collection of other resources, a non-
virtual object (e.g. a person), and so on. In other
words, any concept that might be the target of an
author's hypertext reference must fit within the
definition of a resource. A resource is a conceptual
mapping to a set of entities, not the entity that
corresponds to the mapping at any particular point
in time
Representations
REST components perform actions on a resource
by using a representation to capture the current or
intended state of that resource and transferring that
representation between components. A
representation is a sequence of bytes, plus
representation metadata to describe those bytes.
Other commonly used but less precise names for a
representation include: document, file, and HTTP
message entity, instance, or variant.
A representation consists of data, metadata
describing the data, and, on occasion, metadata to
describe the metadata (usually for the purpose of
verifying message integrity). Metadata is in the
form of name-value pairs, where the name
corresponds to a standard that defines the value's
structure and semantics. Response messages may
include both representation metadata and resource
metadata: information about the resource that is
not specific to the supplied representation.
Connectors
REST uses various connector types, summarized
in Table 5-2, to encapsulate the activities of
accessing resources and transferring resource
representations. The connectors present an abstract
interface for component communication,
enhancing simplicity by providing a clean
separation of concerns and hiding the underlying
implementation of resources and communication
mechanisms. The generality of the interface also
enables substitutability: if the users' only access to
the system is via an abstract interface, the
implementation can be replaced without impacting
the users. Since a connector manages network
communication for a component, information can
be shared across multiple interactions in order to
improve efficiency and responsiveness.
REST Connectors
Connector Modern Web Examples
client libwww, libwww-perl
server libwww, Apache API, NSAPI
cache browser cache, Akamai cache network
resolver bind (DNS lookup library)
tunnel SOCKS, SSL after HTTP CONNECT
All REST interactions are stateless. That is, each
request contains all of the information necessary
for a connector to understand the request,
independent of any requests that may have
preceded it. This restriction accomplishes four
functions: 1) it removes any need for the
connectors to retain application state between
requests, thus reducing consumption of physical
resources and improving scalability; 2) it allows
interactions to be processed in parallel without
requiring that the processing mechanism
understand the interaction semantics; 3) it allows
an intermediary to view and understand a request
in isolation, which may be necessary when
services are dynamically rearranged; and, 4) it
forces all of the information that might factor into
the reusability of a cached response to be present
in each request.
Components
REST Components
Component Modern Web Examples
origin
Apache httpd, Microsoft IIS
server
gateway Squid, CGI, Reverse Proxy
CERN Proxy, Netscape Proxy,
proxy
Gauntlet
Netscape Navigator, Lynx,
user agent
MOMspider
Resources
The fundamental concept in any RESTful API is
the resource. A resource is an object with a type,
associated data, relationships to other resources,
and a set of methods that operate on it. It is similar
to an object instance in an object-oriented
programming language, with the important
difference that only a few standard methods are
defined for the resource (corresponding to the
standard HTTP GET, POST, PUT and DELETE
methods), while an object instance typically has
many methods.
Resources can be grouped into collections. Each
collection is homogeneous so that it contains only
one type of resource, and unordered. Resources
can also exist outside any collection. In this case,
we refer to these resources as singleton resources.
Collections are themselves resources as well.
Collections can exist globally, at the top level of
an API, but can also be contained inside a single
resource. In the latter case, we refer to these
collections as sub-collections. Sub-collections are
usually used to express some kind of “contained
in” relationship. We go into more detail on this
in Relationships.
The diagram below illustrates the key concepts in
a RESTful API.
We call information that describes available
resources types, their behavior, and their
relationships the resource model of an API. The
resource model can be viewed as the RESTful
mapping of the application data model.
Resource Data
Resources have data associated with them. The
richness of data that can be associated with a
resource is part of the resource model for an API.
It defines for example the available data types and
their behavior.
Based on my experience, I have developed a
strong conviction that the JSON data model has
just the right “richness” so that it is an ideal data
model for RESTful resources. I would recommend
that everybody use it.
In JSON, just three types of data exist:
scalar (number, string, boolean, null).
array
object
Scalar types have just a single value. Arrays
contain an ordered list of values of arbitrary type.
Objects consist of a unordered set of key:value
pairs (also called attributes, not to be confused
with XML attributes), where the key is a string and
the value can have an arbitrary type. For more
detailed information on JSON, see the JSON web
site.
Why the strong preference for JSON? In my view,
JSON has the right balance between
expressiveness, and broad availability. The three
types of data (scalars, arrays and objects) are
powerful enough to describe in a natural way
virtually all the data that you might want to expose
as resource, and at the same time these types are
minimal enough so that almost any modern
language has built-in support for them.
XML would be the other obvious contender.
Actually, in the final incarnation of the RHEV-M
API, XML is used to describe resources, via an
XMLSchema definition. With hindsight, I believe
that the XML data model is a bad choice for a
RESTful API. On one side, it is too rich, and on
the other side, it lacks features. XML, as an SGML
off-shoot, is in my view great for representing
structured documents, but not for representing
structured data.
Features of XML that are too rich include:
Attributes vs elements. An XML element can have
both attributes as well as sub-elements. A data
item associated with a resource could be encoded
in either one, and it would not be clear beforehand
which one a client or a server should use.
Relevance of order. The order between child-
elements is relevant in XML. It is not natural in
my view for object attributes to have ordering.
The limitations of the XML data model are:
Lack of types. Elements in XML documents do
not have types, and in order to use types, one
would have to use e.g. XMLSchema. XMLSchema
unfortunately is a strong contender for the most
convoluted specification ever written.
Lack of lists. XML cannot natively express lists.
This can lead to issues whereby it is not clear
whether a certain element is supposed to be a list
or an object, and where that element ends up being
both.
Application Data
We define the data that can be associated with a
resource in terms of the JSON data model, using
the following mapping rules:
Resources are modeled as a JSON object. The type
of the resource is stored under the special
key:value pair “_type”.
Data associated with a resource is modeled as
key:value pairs on the JSON object. To prevent
naming conflicts with internal key:value pairs,
keys must not start with “_”.
The values of key:value pairs use any of the native
JSON data types of string, number, boolean, null,
or arrays thereof. Values can also be objects, in
which case they are modeling nested resources.
Collections are modeled as an array of objects.
We will also refer to key:value pairs as attributes
of the JSON object, and we will be sloppy and use
that same term for data items associated with
resources, too. This use of attributes is not to be
confused with XML attributes.
REST Metadata
In addition to exposing application data, resources
also include other information that is specific to
the RESTful API. Such information includes
URLs and relationships.
The following table lists generic attributes that are
defined and have a specific meaning on all
resources. They should not be used for mapping
application model attributes.
Attribute Type Meaning
Attribute Type Meaning
Identifies the unique ID of a
id String
resource.
Identifies the URL of the current
href String
resource.
Identifies a relationship for a
resource. This attribute is itself
link Object
an object and has “rel” “href”
attributes.
Other Data
Apart from application data, and REST metadata,
sometimes other data is required as well. This is
usually “RPC like” data where a setting is needed
for an operation, and where that setting will not
end up being part of the resource itself.
One example that I can give here is where a
resource creation needs a reference to another
resource that is used during the creation, but where
that other resource will not become part of the
resource itself.
It is the responsibility of the API code to merge the
application data together with the REST metadata
and the other data into a single resource, resolving
possible naming conflicts that may arise.
Representations
We have defined resources, and defined the data
associated with them in terms of the JSON data
model. However, these resources are still abstract
entities. Before they can be communicated to a
client over an HTTP connection, they need to be
serialized to a textual representation. This
representation can then be included as an entity in
an HTTP message body.
The following representations are common for
resources. The table also lists the appropriate
content-type to use:
Type Content-Type
application/x-resource+json
JSON
application/x-collection+json
application/x-resource+yaml
YAML
application/x-collection+yaml
application/x-resource+xml
XML
application/x-collection+xml
HTML text/html
Note: all these content types use the “x-”
experimental prefix that is allowed by RFC2046.
JSON Format
Formatting a resource to JSON is trivial because
the data model of a resource is defined in terms of
the JSON model. Below we give an example of a
JSON serialization of a virtual machine:
{
"_type": "vm",
"name": "A virtual machine",
"memory": 1024,
"cpu": {
"cores": 4,
"speed": 3600
},
"boot": {
"devices": ["cdrom", "harddisk"]
}
}
YAML Format
Formatting to YAML is only slightly different
than representing a resource in JSON. The
resource type that is stored under the “_type”
key/value pair is serialized as a YAML ”!type”
annotation instead. The same virtual machine as
above, now in YAML format:
!vm
name: A virtual machine
memory: 1024
cpu:
cores: 4
speed: 3600
boot:
devices:
- cdrom
- harddisk
XML Format
XML is the most complex representation format
due to both its complexity as well as its
limitations. I recommend the following rules:
Resources are mapped to XML elements with a tag
name equal to the resource type.
Attributes of resources are mapped to XML child
elements with the tag name equal to the attribute
name.
Scalar values are stored as text nodes. A special
“type” attribute on the containing element should
be used to refer to an XML Schema Part 2 type
definition.
Lists should be stored as a single container
element with child elements for each list item. The
tag of the container element should be the English
plural of the attribute name. The item tag should
be the English singular of the attribute name. Lists
should have the “xd:list” type annotation.
The same VM again, now in XML:
<vm
xmlns:xs="http://www.w3.org/2001/XMLSchema
">
<name type="xs:string">My VM</name>
<memory type="xs:int">1024</memory>
<cpu>
<cores type="xs:int">4</cores>
<speed type="xs:int">3600</speed>
</cpu>
<boot>
<devices type="xs:list">
<device type="xs:string">cdrom</device>
<device type="xs:string">harddisk</device>
</devices>
</boot>
</vm>
HTML Format
The exact format of a HTML response can be API
dependent. HTML is for human consumption, and
the only requirement is therefore that it be easy to
understand. A simple implementation may choose
the following representation:
For a collection, a <table> with a column per
attribute where each object is listed in a separate
row.
For a resource, a <table> with two columns, one
with all the attribute names, one with the
corresponding attribute value.
Content-Types
As can be seen above, I am advocating the use of a
generic content types “application/x-
resource+format” and “application/x-
collection+format”. In my view this represents the
right middle ground between two extremes that are
commonly found in RESTful APIs:
Some RESTful APIs only use the “bare” XML,
JSON or YAML content types. An example of
such as API is the Red Hat Enterprise
Virtualization API. In this case, the content type
expresses nothing but the fact that an entity is in
XML, JSON or YAML format. In my view, this is
not sufficient. Resources and collections have
some specific semantics around for example the
use of “href” attributes, “link” attributes, and
types. Therefore, these are a specialization of
XML, JSON and YAML and should be defined as
such.
Other RESTful APIs define a content-type for
every resource type that exists in the resource
model. Examples of such APIs include for
example VMware’s vSphere Director API. In my
view, this is not proper either. Specifying detailed
content types invites both the API implementer, as
well as a client implementer to think about these
types as having specific interfaces. In my view
though, all resources should share the same basic
interface, which is defined by the RESTful design
principles and expressed by the “application/x-
resource” content type.
One reason that is sometimes given in favor of
defining detailed content types is that this way, the
content type can be associated with a specific
definition in some type definition language (such
as XMLSchema). This, supposedly, facilitates
client auto-discovery because a client can know
available attributes for a certain type. I go into a
lot of detail on this topic in Forms but the
summary is that I do not agree with this argument.
Selecting a Representation Format
Clients can express their preference for a certain
representation format using the HTTP “Accept”
header. The HTTP RFC defines an elaborate set of
rules in which multiple formats can be requested,
each with its own priority. In the following
example, the client tells the API that it accepts
only YAML input:
GET /api/collection
Accept: application/x-collection+yaml

1. JSON Specifications
Douglas Crockford originally created JSON in
2001, and initially standardized it in 2006
under RFC 4627 through the IETF. In 2013, Ecma
International also standardized JSON
under ECMA 404.
In March 2014, Tim Bray corrected errata with the
original IETF 4627 in IETF RFC 7158 and RFC
7159.
The new specifications remove inconsistencies
with other specifications of JSON, repairs
specification errors, and offer experience-based
interoperability guidance.
2. JSON File and MIME Type
The standard file type for storing a JSON
document in the filesystem is .json.
JSON’s Internet Assigned Numbers Authority
(IANA) media (or MIME) type is application/json.
3. JSON Document
A JSON document may contain text, curly braces,
square brackets, colons, commas, double quotes,
and maybe a few other characters.
Primarily, a valid JSON document can contain two
structures:
An Object surrounded by curly braces and
containing multiple name/value pairs. In various
languages, this is realized as an record, struct,
dictionary, hash table, keyed list, or associative
array.
An Array or Ordered list of values surrounded
by square brackets. In most languages, this is
realized as an vector, list, or sequence.
4. JSON Example
An example JSON document is:
//JSON Object

{
"employee": {
"id": 1,
"name": "Admin",
"location": "USA"
}
}

//JSON Array

{
"employees": [
{
"id": 1,
"name": "Admin",
"location": "India"
},
{
"id": 2,
"name": "Author",
"location": "USA"
},
{
"id": 3,
"name": "Visitor",
"location": "USA"
}
]
}
As we can see, the JSON document consists of
name/value pairs. These name/value pairs reflect
the structure of the data.
JSON (JavaScript Object Notation) is a
lightweight data-interchange format. It is easy for
humans to read and write. It is easy for machines
to parse and generate. It is based on a subset of the
JavaScript Programming Language Standard
ECMA-262 3rd Edition - December 1999. JSON is
a text format that is completely language
independent but uses conventions that are familiar
to programmers of the C-family of languages,
including C, C++, C#, Java, JavaScript, Perl,
Python, and many others. These properties make
JSON an ideal data-interchange language.
JSON is built on two structures:
A collection of name/value pairs. In various
languages, this is realized as an object, record,
struct, dictionary, hash table, keyed list, or
associative array.
An ordered list of values. In most languages, this
is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all
modern programming languages support them in
one form or another. It makes sense that a data
format that is interchangeable with programming
languages also be based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs.
An object begins with {left brace and ends
with }right brace. Each name is followed
by :colon and the name/value pairs are separated
by ,comma.
What is a REST API?
A REST API, or RESTful API, is a type of
application programming interface (API) that
follows the principles of Representational State
Transfer (REST) architectural style. It allows
communication between different applications or
systems over the internet, typically using HTTP
requests and responses. Think of it as a set of
instructions for how to interact with a specific
piece of software or service.
What are the benefits of using APIs?
Increased Efficiency: APIs automate tasks, saving
developers time and resources.
Improved Functionality: APIs provide access to
specialized data and functionality, enhancing
applications.
Easier Integration: APIs simplify communication
between different systems, regardless of their
programming language.
Scalability: APIs enable applications to handle
increased traffic and data volumes.
Flexibility: APIs offer flexibility for developers to
build custom applications and integrations.

What is a URI?
A URI (Uniform Resource Identifier) is a unique
identifier for a resource on the internet, like a web
page, image, or API endpoint. It tells the system
where to find the specific resource you’re
requesting. In REST APIs, URIs often include the
resource type and specific identifier (e.g.,
/users/123).
What are API methods?
API methods are specific actions you can perform
on a resource using the API. Common methods
include GET (retrieve data), POST (create data),
PUT (update data), and DELETE (remove data).
These methods are typically mapped to HTTP
verbs for clear communication.
What are the key design principles of APIs?
Resource-based: Treat data and functionality as
resources with unique identifiers.
Stateless: Each request-response interaction is
independent, and the server doesn’t store state
information.
Cachable: Responses can be cached for improved
performance.
Uniform interface: Use consistent naming
conventions and methods across the API.
Documenting: Provide clear documentation for
developers to understand how to use the API
effectively.
What is JSON?
JSON (JavaScript Object Notation) is a popular
data format for exchanging information between
applications. It uses a human-readable format with
key-value pairs, making it lightweight and easy to
parse. APIs often use JSON to send and receive
data, making it a crucial element in API
communication.
Example JSON File:
{
“name”: “John Doe”,
“age”: 30,
“occupation”: “Software Engineer”,
“interests”: [“coding”, “travel”, “music”],
“address”: {
“street”: “123 Main Street”,
“city”: “Anytown”,
“state”: “CA”,
“zipcode”: “12345”
}
}
This example represents information about a
person in JSON format. It uses key-value pairs to
store data like name, age, occupation, interests,
and address. The address itself is another object
nested within the main object.
Key Benefits of JSON:
JSON uses a simple and clear format with key-
value pairs, making it easy for humans to
understand and edit.
JSON files are compact and require minimal data
overhead, making them ideal for network
transmission and storage.
JSON is not tied to any specific programming
language, making it easily usable in various
development environments.
JSON allows for nested objects and arrays,
providing flexibility in representing complex data
structures.
The structure and data types are readily apparent
within the JSON file, eliminating the need for
separate schema definitions.
JSON is a de facto standard for data exchange,
supported by most programming languages, web
frameworks, and databases.

What it JSON?
JavaScript Object Notation (JSON) is a
lightweight text-based, language-independent data
exchange format. JSON defines a small set of
formatting rules for the portable representation of
structured data. JSON can represent four primitive
types (strings, numbers, boolean values, and null)
and two structured types (objects and arrays).
JSON is used to exchange data between
applications written in many programming
languages, including JavaScript, Java, C++, C#,
Go, PHP, Python, and many others.
How to request data in JSON format?
To get data in JSON format from the server, the
client must explicitly tell the server that it expects
JSON by sending the Accept: application/json
request header. Without the Accept header, the
server may automatically send data in a different
format that it thinks is best for the API
client (based on the UserAgent header), and it
might not be JSON.
JSON Accept Header Example
Accept: application/json
How to send and receive JSON data using
JavaScript?
JSON data is transmitted over the network as a
text string and must be converted to
a JavaScript object before using it. Likewise,
before sending JavaScript objects over the network
in JSON format, they must be converted to strings.
JavaScript has two built-in functions for
converting JavaScript objects to JSON and vice
versa:
JSON.parse() - converts a JSON string to a
JavaScript object.
JSON.stringify() - converts a JavaScript object to a
JSON string.
JSON Request Example
An example of an HTTP GET request to fetch
JSON data from a ReqBin echo URL.
JSON Request Example
GET /echo/get/json HTTP/1.1
Host: reqbin.com
Accept: application/json

The server response to our client's request.


JSON Response Example
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 19

{"success":"true"}

The server returned JSON in the body of the


HTTP response message. The Content-Length: 19
header indicates the length of the JSON data in the
response body, and the Content-Type:
application/json response header indicates the type
of data.
JSON MIME Type
The official MIME type for JSON is
application/json:
JSON Content-Type Header Example
Content-Type: application/json

Learn API REST JSON by Example


Introduction
REST APIs and JSON have become essential
building blocks of modern web and mobile
applications. As developers, having a solid grasp
of REST API principles and JSON is a must-have
skillset in today's market. The demand for
developers proficient in APIs continues to grow
rapidly.

In this beginner's guide, we'll provide hands-on


examples to help you gain a practical
understanding of REST APIs and JSON. You'll
learn core concepts like API requests, responses,
status codes, endpoints, parameters, headers, and
more. We'll also cover JSON syntax, data types,
and structures with realistic examples you can
apply right away.

By the end, you'll have the knowledge to start


building your own RESTful APIs and leverage
JSON for sending and receiving data. Let's dive in!

REST API Basics


A REST (REpresentational State Transfer) API is
an architectural style for building web APIs. At a
high level, REST APIs expose various HTTP
endpoints that enable the client to perform
operations on resources using standard HTTP
methods like GET, POST, PUT, DELETE.

REST APIs follow a client-server model where the


client sends requests and the server sends
responses. The key principles of REST include:
REST Architectural Constraints
Uniform interface - Resources are uniquely
addressable using URIs and manipulated via
standard HTTP methods. This simplifies the
interface between client and server.
Client-server separation - Client and server can
evolve independently without affecting each other.
Statelessness - No client session state is stored on
the server between requests. Each request contains
full context.
Cacheability - REST responses should ideally be
cacheable to improve performance.
Layered system - REST allows for intermediaries
like proxies without clients knowing about them.
REST API Anatomy
Resources - The objects/data entities exposed by
the API, like users, products, etc.
CRUD operations - APIs allow creating, reading,
updating, deleting resources.
HTTP verbs - GET, POST, PUT, DELETE used
for corresponding CRUD operations.
Endpoints - The URIs used to access resources,
like /api/users.
Parameters - Extra pieces of data passed along in
requests like URL params or query strings.
Headers - Provide metadata like authorization,
content-type, etc.
Status codes - Indicate API request success/failure,
like 200 OK, 404 Not Found.
For example, a simple DevHunt API could expose
/users and /tools endpoints that allow CRUD
operations on user and tool resources using
appropriate HTTP methods and status codes.

JSON Basics
JSON (JavaScript Object Notation) is a
lightweight data interchange format commonly
used with REST APIs for serializing and
transmitting structured data over the network.

JSON represents data as human-readable text in


key-value pairs and ordered lists, which makes it
easier to parse than formats like XML. Let's look
at some JSON basics:

JSON Syntax
Objects - Enclosed in {} braces with "key":
"value" pairs.
Arrays - Enclosed in [] brackets and contain
ordered values.
Data types - String, number, boolean, null.
Nesting - Objects and arrays can be nested.
Escaping - Certain characters are escaped like "\n".
Working with JSON
Serialization - Converting objects to JSON strings
to transmit.
Deserialization - Parsing JSON back to native
objects.
Validation - Checking if JSON is well-formed.
Querying - Extracting values from JSON objects.
Manipulation - Modifying JSON data
programmatically.
Tools & libraries - Helper modules like json in
Python.
Compared to XML, JSON provides a lightweight
and compact syntax that integrates easily with
JavaScript. Overall, JSON is ideal for web APIs
due to its terseness, readability, and wide language
support.

Example REST API Walkthrough


Let's go through an example workflow of
interacting with a sample DevHunt REST API via
cURL or Postman to see the concepts in action.

We'll make requests to:

GET /tools - Retrieve a list of tools.


GET /tools/{id} - Get a specific tool.
POST /tools - Create a new tool.
PUT /tools/{id} - Update a tool.
DELETE /tools/{id} - Delete a tool.
For each request, we can analyze:

The HTTP method - GET, POST, etc.


Any request parameters, like the {id}.
The request headers, like Content-Type.
The request body containing any JSON data.
The response status code - 200, 201, 404, etc.
The raw JSON response body.
As we walk through examples, we'll discuss what
the different status codes mean and how to
troubleshoot errors like 400 or 500 responses.

This hands-on API exploration will really solidify


your understanding of real-world API concepts.

JSON Examples
Here are some sample JSON code snippets to
illustrate the syntax and structure for typical use
cases:

User Profile

{
"first_name": "John",
"last_name": "Doe",
"age": 35,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": 12345
}
}
Product Data

[
{
"id": "p123",
"name": "T-Shirt",
"color": "blue",
"price": 29.99,
"tags": ["apparel", "clothing"]
},
{
"id": "p456",
"name": "Backpack",
"color": "green",
"price": 79.99,
"tags": ["accessories", "gear"]
}
]
API Response

{
"status": 200,
"message": "Success",
"data": {
"id": "user123",
"username": "jdoe",
"email": "[email protected]"
}
}

You might also like