0% found this document useful (0 votes)
10 views27 pages

API Development Manual

This manual describes the development of APIs. It explains that REST APIs have become popular to separate the front and back end of applications and facilitate scalability. REST APIs are stateless, which means they do not maintain state between calls, improving scalability. It also describes the uniform interface of REST APIs, which use resources identified by URIs instead of remote procedure calls as in SOAP APIs.
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)
10 views27 pages

API Development Manual

This manual describes the development of APIs. It explains that REST APIs have become popular to separate the front and back end of applications and facilitate scalability. REST APIs are stateless, which means they do not maintain state between calls, improving scalability. It also describes the uniform interface of REST APIs, which use resources identified by URIs instead of remote procedure calls as in SOAP APIs.
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/ 27

API Development Manual

The provided text is a URL and does not contain translatable content. Page 1 of 27
API Development Manual

Introduction: Development manual of


APIs

In this manual, we aim to provide information related to API development, one of the
keys to the modern development of applications, for the web or for devices.

Developing based on an API has many advantages, as we will explain here. Among them, it allows us to
separate the backend and frontend of applications, offer a better user experience
advances and facilitates the scalability of the project as it grows.

The API development manual is not intended to be a description of API implementation processes.
Well, it would take hundreds or thousands of pages to cover all the possible situations in which you can
to find you, just like dozens of languages, databases, frameworks, etc.

Instead, our goal is to gather articles that serve as a guide for people who intend to get started.
in the development of APIs, regardless of the approach or technology stack to be used. Or for reading for the
people who are interested in these topics and want to know how the applications work
modern

You can find this manual online at:


The provided text is a URL and does not require translation.

The provided text is a URL and does not contain translatable content. Page 2 of 27
API Development Manual

Authors of the manual

The following individuals have participated as authors by writing articles for this manual.

Miguel Angel Alvarez

Miguel is the founder of DesarrolloWeb.com and the online training platform.


EscuelaIT. It began in the world of web development in 1997,
turning your hobby into your job.

Eduard Tomàs

Passionate about computer science, video games, role-playing, and... beer.


Consultant at Pasiona and MVP in #aspnet

The provided input is a URL and does not contain translatable text. Page 3 of 27
API Development Manual

What is REST

You may know them from REST APIs. We explain why they have become so popular.
world of the Internet and what characteristics these systems have.

Currently, REST APIs are really in vogue: it seems that any application must provide its
“REST API”. But... what does a REST API really mean?

REST stands for 'REpresentational State Transfer', which translated would be 'transfer of'
representation of state,” which doesn’t clarify much either, but contains the key to what it means. Because
The key to REST is that a REST service is stateless, which means that, between two
any calls, the service loses all its data. That is, a service cannot be called
REST and pass some data (e.g. a username and a password) and expect it to 'remember us' in the next one.
request. Hence the name: the state is maintained by the client and therefore it is the client who must pass the
state in each call. If I want a REST service to remember me, I must tell it who I am in each
call. This could be a username and a password, a token or any other type of credentials, but
I have to pass them in each call. The same applies to the rest of the information.

Not having state is a clear disadvantage: having to pass the state in each call is, at a minimum,
tedious, but the trade-off is clear: scalability. To maintain a state, some place is required
(generally memory) where to store all the states of all clients. More clients, more
memory, until finally we may no longer be able to accept more clients, not due to lack of CPU, but due to
memory. It is something similar to what happens with traditional web (which is also stateless). Whatever the
technology with which you develop for the web, you surely know that you can create what is called a
"session". The session data is maintained between requests and is per user. The classic example of
the session can be a shopping cart, among the different web requests, the information of the cart
purchase remains (note! there are other alternatives to implement shopping carts).

As a general rule, the session is stored in the server's RAM, so it's easy to run out of
memory if we introduce too much data in the session (or have many simultaneous users). By
Supposedly, we can use several servers, but as web developers well know, moving the
session stored in memory between servers is generally impossible or highly inefficient, which

Unable to access external URLs. Page 4 of 27


API Development Manual

it penalizes load balancing, which in turn results in lower scalability and lower fault tolerance.
There are intermediate solutions, such as saving the session in a database, but their impact on the
performance is usually very great. In fact, the main advice for developing web applications
highly scalable means: not using the session.

Thus, being stateless is the main characteristic of REST, although of course not the only one.
unique. Thus, any REST service (if it wants to be deserving of that name) should be stateless, but
not every stateless service is REST. There are other factors, but we will highlight the one that the English
they call it 'uniform interface' and it is what differentiates a classic web service (oriented to RPC) from a service
REST.

SOAP and REST


SOAP is the acronym for 'Simple Object Access Protocol' and is the protocol that underlies the technology.
which we commonly refer to as 'Web Services' or web services. SOAP is a protocol
extraordinarily complex designed to provide solutions to almost any need regarding
communications refers to, including advanced aspects of security, transactional capabilities, messaging
secured and others. When SOAP was released, a golden age of web services was experienced. Although the
the first implementations were what were called WS1.0 and barely supported any advanced scenarios,
everyone was paying the price of using SOAP, as it seemed clear that it was the standard that would dominate the
future. Over time, the WS-* specifications were released, which provided advanced solutions, but at the same time
as the capabilities of SOAP grew, so did its complexity. In the end, SOAP web services end up being
a monster with many capabilities but that in most cases we do not need.

On its part, REST is simple. REST does not aim to provide solutions for everything and therefore we do not pay with a
too much complexity a power that we may not need.

Uniform interface
A fundamental difference between a classic web service (SOAP) and a REST service is that the former is
oriented to RPC, that is, to invoke methods on a remote service, while the second is
resource-oriented. That is, we operate on resources, not on services.

In a REST API, the idea of 'service' as such disappears. What we have are resources, accessible by
identifiers (URIs). On those resources we can perform actions, generally differentiated through
of distinct HTTP verbs.

Thus, in a classic web service (SOAP) we would have a service called BeerService that would have a method
GetAll call that would return all the beers. The idea, regardless of the technology used
To consume the web service, a method (GetAll) of a remote service (BeerService) is called.
Similarly, to obtain a specific beer, we would call the GetById() method, passing in the id.
of the beer. Hence, it is said that they are oriented towards RPC (Remote Procedure Call - Method Call)
remote).

On the other hand, in a REST service, the very idea of service fades away. Instead, we are left with the idea of
a 'resource', let's call it 'Beer Collection', which has a URI that identifies it, e.g. /Beers. Thus, if
When I invoke that URI, I should obtain a representation of that resource, that is, I should get the listing of
all the beers.

No text provided for translation. Page 5 of 27


API Development Manual

To obtain data about a beer, there will be another resource (beer) with an associated URI. In addition, among the
resources there are relationships: it is clear that a beer is part of the 'Beer Collection' so it seems
It's logical that from the entire collection (/Beers) I can access one of its elements with a URI like
/Beers/123, siendo "123" el ID de la cerveza.

Let's return to our SOAP service: to register a beer we would call a method 'AddBeer' of
our 'BeerService', and we would pass the beer to add. Instead, in our REST API add a
beer consists of using the URI of that beer, (e.g. /Beers/456 if we are adding the beer with ID
456) using POST or PUT as the HTTP verb and placing the beer data in the body of the
request. The URI to access the beer with ID 456 is always /Beers/456 and it is the HTTP verb (GET,
POST, PUT, DELETE,... indicates the operation we want to perform with that beer.

This article is by Eduard Tomàs


It was first published on 04/25/2014
Available online atThe content of the provided URL cannot be accessed or translated.

The provided text appears to be a URL and does not contain translatable content. Page 6 of 27
API Development Manual

Advantages and disadvantages of REST API


for development

Study on the advantages and disadvantages of developing websites and applications of all kinds
using a REST API as a communication model between the frontend and the backend.

We are facing a trend that is spreading widely in the realm of current technology, REST, which
supports a new model of software development that is different, capable of providing several advantages in the cycle of
life of applications.

In this article, we will explain in detail what we mean by API-based development.


RESTy we are going to study the advantages and disadvantages of this model. We will review concepts and techniques.
modern development (we are in the year 2014) that everyone should at least be aware of.

Introduce REST
Inevitably, we must start by explaining what REST is. That word that we have all read, heard,
seen and understood only perhaps halfway. And the truth is that this point will be easy because we have an article
previously explained it wonderfully, so I will just link to it:What is REST.

Architecture of a development based on REST API


Once we know exactly the characteristics of REST, we can consider what it is like.
REST-based application. There could really be many answers since we can use APIs.
to create a multitude of websites. For example, we could use the Twitter REST API to create a
service based on that network or the YouTube API to create a website that displays videos from different
ways. But that is not what I am referring to in this article.

In this case, I want to propose a model that perfectly leverages its REST capabilities where you
or your team is the one developing your own API and where you are the consumer of it.

The provided text is a URL and does not contain translatable content. Page 7 of 27
API Development Manual

Note: To clarify, saying that commonly until now we always had a client (browser) and a
server. The client would make a request for a URL and receive an HTML page, with its styles, etc. That
The page had an HTML that rendered in the browser and produced the presentation we desired.
That situation has been useful to us for a long time and continues to be today, but now there are
other solutions that provide us with other possibilities. You have to look at all this through the prism of
current technological moment. The goal remains to create applications, however, in many cases
we are not going to think only about creating web applications, but also apps for mobile or any other type
of system or device.

Well, now in a development based on REST API we will have a schema like the one you can see in
this image:

The client always initiates a request, but now it is not made by the user in 'raw' to the server.
but goes through JavaScript. Our client-side language is the one that will request a resource from the server.
to the server.

The server and the web client communicate in an information exchange format such as
JSON, although it could be another language like XML.

The important thing is that the client does not receive HTML to render, but simply the data that has been
generated as a response. That is to say, the server does not write HTML, but only generates the data for
send them to the client.

What server technologies do you use to implement REST?

It's independent, you can have a server that works with PHP, Java, Python, NodeJS, or whatever you prefer, or
the project imposes on you. Both the language and the database are important because they serve us to
process the request and generate the response, but it doesn't matter how you do it on the server. Just that
the answer should be delivered in that language of information exchange that you are using, generally
JSON.

http://desarrolloweb.com/manuales/manual-development-api.html Page 8 of 27
API Development Manual

What JS libraries?

We are not really obligated to use any. What will be clear is that if you are producing one
On the web client, you will use Javascript, but the library you have to make things easier is irrelevant.

Currently, due to opportunities, community, and ease of development, professionals are


opting for AngularJS, but you will really use the one you feel comfortable with.

Any server-side library?

There must be hundreds, also depending on the language you are using on the server. If it is with PHP
you can use Laravel, Symfony, or microframeworks like Slim. If you are using NodeJS, probably
You find Express or Sails.js useful. These are just to name a few, since in this case it all depends.
a lot of the technology you are using on the server.

What type of applications are suitable for this architecture?

This is a good question, because really the development based on REST API is not for every type.
of project. If you are creating a website and you plan for your site to always be just that 'a web', maybe it is
unnecessary to develop based on an API. For example, a content-focused site, like a blog or a
a company's page where it offers its products, services, and contact methods makes no sense
develop it based on an API. Now, if what you are offering is an online service or you are conducting a
web management application, so it perfectly fits the philosophy of REST.

In general, if you think that your system in the future could be accessed not only from a web page, but
also from a mobile app or from another type of application, the advantages of REST will be
especially useful. In summary, if you suspect that the data or services you are offering in the future
can be consulted from other systems, you are interested in using REST. There are even professionals who
they think that, even though you may not currently be thinking about those data or services possibly becoming
consulted from other systems outside your web, it is worth using REST because it is the solution that
it will provide you with greater scalability. You will see all of this better as soon as we address the advantages /
inconveniences.

Advantages of REST-based development


We list a series of advantages that you will find in a development based on REST API.

client/server separation

As independent systems (they only communicate with an exchange language like JSON) you can
develop autonomous projects, autonomous teams. The client does not care how the API is made and to the
the server does not care what you are going to do with the data it has provided.

If you need to evolve/refactor either the back or the front, it can be done separately.
as long as the API interface is maintained.

You can make several frontends with a single backend (frontend doesn't have to be just web, it can be an app for
Android another for an iOS App, etc.)

The content at the provided URL cannot be accessed for translation. Page 9 of 27
API Development Manual

Note: Be careful with this. Yes, they are independent, BUT both teams need to have a lot of communication.
to know what to do and how to do it; unfortunately, this lack of communication is a classic mistake and
very common that always leads to time losses and having to repeat the work.

In this regard, another very important advantage is the possibility of creating as many frontals as you need with the
same API. You start by developing a website, but with the same API you can also develop a
application for iOS, Android and if you like tomorrow for Windows 8, Windows Phone, the next Windows
10, Blackberry, FirefoxOS and as many as come in the future to fit with your business strategy.

2. Independence of technologies / languages

You can develop in any type of technology or language with which you feel comfortable or with which
you can shorten your development times, or fit with the philosophy or needs of your project. It is
It doesn't matter if you completely change the technologies with which your API is implemented in the future.
REST, as long as you respect 'the contract', meaning that you continue to have the same operations in the API and
they do the same things they are supposed to do.

Note: As suggested in the comments of the articles, it is worth insisting that JSON is not consumed.
not only from JavaScript, but we can consume it from any language/technology, from
PHP for server-side web development, as well as Python, .NET, Objective C or Swift for
iOS applications, Java for Android applications. These are just a few examples because there are hundreds of
languages where we can work with JSON.

3. Reliability, scalability, flexibility

In the end, you only need to worry that the client/server connection is correct. You can make changes in
your server, languages, databases, etc. and as long as you return the data that needs to be returned everything will go correctly.

Scalability because you can grow as much as you need at any moment. Your API can respond to
other types of operations or it can be versioned as much as you want. Also, your programming on the side of
the client can grow everything necessary over time, even as we said, create other fronts, not just
web, also for Apps for any device.

Invalid input. Please provide text for translation. Page 10 of 27


API Development Manual

When executing your application, you also have much greater flexibility. The front pages...
you can send from some servers and the APIs can be hosted on independent servers, as many
as you need. Due to the characteristics of REST (mainly not maintaining state), it does not matter what
the server handles each request, since it is the client itself that has to send the status to the server, thus
that load balancing is much simpler than in traditional applications where the front is
mixed with the back. You also have the approach of 'micro APIs', in which you can divide the
processes on different servers that handle different types of API operations.

4. User experience

Although that depends more on how the client side is made, theoretically web development
Based on an API, it can provide better performance than a traditional one. When you make a request to the server
What you have as a response are flat data, which require shorter transfer times than those.
you would receive the same data mixed with the HTML/CSS of the presentation. In this type of applications
You don't need to reload the page, although this is not a specific advantage of development based on
REST, but from the use of Ajax in general, which allows us to achieve web applications that resemble
more to desktop applications

5. REST requires fewer server resources

This is not necessarily true although it can often be inferred in many cases. There are many opinions on
around REST. We base that statement on these reasons:

Stateless, does not require memory, can handle more requests

It does not require writing HTML, therefore you have less processing on the server.

Disadvantages of REST-based development


We need to change our way of thinking, so work teams have to adapt. Everyone
They must break away from the idea that everything is on a server and that everything is there to develop your ...
needs. In a REST scheme, you can have several servers where some do not know that others exist.
They exist. You don't know if a user has logged into a server and if you have sent them certain data. You also don't
Do you really know which server a request can fall on? Breaking away from that scheme of everything being in the
same server, I have all my classes and all parts of my application centralized is one of the points
that can turn out to be more complicated.

In REST APIs, we do not maintain state, and that means you have to set up your own infrastructure to
to be able to preserve the whole application. Generally, you will send a token indicating who you are to
server and what you have already done in your application.

Initially, you may incur longer development times because you have to set everything up.
your API system. However, in the future, especially when that API is going to be consumed from others
systems, you can reclaim the additional time spent and gain a lot of speed, because the heart of the
new systems (the API) you already have developed. In any case, thanks to REST and the separation of
code will also require less maintenance.

Greater rigidity in development may occur under certain circumstances, especially when there are two.

Unable to access the provided link for translation. Page 11 of 27


API Development Manual

independent projects, your backend based on REST and the frontend(s), situations of des- may arise.
synchronization. For example, from the client you detect that you need new things from the API and the people in charge of
Creating them on the server side may be at a different pace and take longer to develop.

It requires more knowledge, it forces you to step out of the comfort zone that we might be in. Apart from
to know your languages, databases, libraries, you will need to learn about the HTTP protocol.

Conclusion
Ultimately, you will notice that the advantages and disadvantages of API REST-based development are very
interconnected. What may start as an advantage can pose a disadvantage at another point in your
application. However, as we have mentioned, there are many situations in which to develop based on
An API can provide us with a great advance.

We hope you found this article helpful.

Note on authorship: This article is the result of research by the author, based on
the experience and the conversation in a #programadorIO where we explain just the
characteristics and possibilities of API-based development. Therefore, we must share the credit with
our companions:

Carlos Ruiz Ruso@micromanteErick Ruiz de Chavez@erickrdchRoberto Segura@phproberto

This article is the work of Miguel Angel Alvarez


It was first published on 12/19/2014
Available online athttp://desarrolloweb.com/articles/advantages-disadvantages-apirest-development.html

Invalid input. Please provide text for translation. Page 12 of 27


API Development Manual

Token authentication

What is token authentication, the usual procedure for logging users into APIs
REST and remind them for future accesses to the web service.

In this article, we are going to address, conceptually, a recurring practice when it comes to maintaining the
security of a REST API, such as token authentication. As we say, it is common in
REST architectures, although it can also be used for any other, for example GraphQL or others.
mechanisms to implement web services.

Token authentication is something that must be done on the server side and therefore its
implementation largely depends on the technologies we are using in the backend. Without
embargo, we always work with the same application flow and the concepts that we are going to describe to
the following are perfectly valid for any language, database, or type of server that
we may be using.

What is token authentication?


For those who do not have any notions, we will explain, in general, what an authentication model would be like.
suitable for APIs.

If there is something characteristic of APIs, REST or any other architecture, it is that they do not manage state and therefore
so they don't have sessions. In the article ofWhat is RESTwe already had the opportunity to give more details about this,
so we are not going to repeat ourselves. What stands out now is that, as a consequence of not having a state and
not having sessions on the server for each user, the backend is unable to remember the user between
call and call to the API.

To prevent the user from having to provide their key and password on each call, a token is used, which is nothing more than
a very long text string, encrypted with a key. As the login is made, the server returns to
The client receives a token and in future accesses, the client provides that token to certify that they are authenticated.

The text provided is a URL and cannot be translated. Page 13 of 27


API Development Manual

Note: Developing based on API has various advantages, such as providing the possibility for others to work.
with your web services from your applications. But even if it were only you who is going to use an API and not the
publicly available, there are also various advantages. If you want to add some more information
can you also read the articleOne backend, different frontends.

Authentication and authorization flow


In summary, the workflow for token authentication, in the context of frontend development, is
you can see in the following image:

A.- The client sends the login data

Through a form on the page, the user and access key are collected. This data will be sent to the
server. At this point, two things can happen:

1. If the login is correct, the client is considered authenticated. Then a token is generated on the side of the
server, which will be sent back to the client.
If the login was not correct, then an error code is sent to the client.

B.- Store the token

In the event that a correct authentication attempt is made, and therefore the server would return us the
token, on the client side, the token must be stored in order to use it later.

The ideal would be to store the token in the browser, in a place where it can be accessed in the future.
queries. That is to say, it would be interesting to provide some persistence system, so that, for example, if the
The user refreshes the page or accesses the same web after a few minutes, the generated token is available.
previously and the user should not be forced to go through the login process again. The most normal
to store the token it would be the LocalStorage of the browser.

C.- Sending the token in subsequent accesses

Every time the client, once authenticated, wants to access a resource of that API again, then
He will have to send the token to the server to inform it that it is himself and that he has already authenticated correctly.
in a previous step.

Upon receiving the token, the server will have to verify it and, if it finds it valid, it will know that it corresponds to a

http://desarrolloweb.com/manuales/manual-desarrollo-api.html Page 14 of 27
API Development Manual

user of your application, so they will be able to grant access to the requested resource.

Other important situations of user control flow

In addition to the user authentication process and subsequent authorization for access to the API, there is a
a couple of additional cases that we need to implement for the user control flow in the application.

Upon starting the application

When starting the entire application startup process, regardless of the JavaScript framework being used
using, it may happen that a token is already stored in a persistence space in the
browser.

Therefore, also on the frontend side, the client must check if it has the token in the
local storage.

1. If you have it, you must verify that it is correct. To do this, you will send a request to the server, which is
who can verify that token. a) If it is correct then they are authenticated. With what the client
should modify the application state to show that the user is logged in. b) If not
correct, so it is understood that the token is not valid and therefore it would be logical to delete it from the
local storage and maintaining application state, showing that it is not authenticated.
2. b) If the client does not have the token in a storage space, it is understood that they are not.
authenticated and we do not need to verify anything. In this case, the application's status should
demonstrate that you are not logged in.

When logging out

The procedure for logging out involves deleting the token from the browser's local storage. Additionally
In the application, the status should be modified to indicate to the user that they are not logged in.

Token and refresh token expiration

Another thing we haven't mentioned in this flow arises from the expiration of the token. The token
It generally has an expiration time, which is set on the server at the time the token is generated.

During the validity period of the token, it may be used to authorize access to certain resources by
part of the authenticated client. However, if the token has expired, then the server will reject it and the
the client will not be able to access the requested information or operation.

To establish a flow to mitigate possible issues due to token expiration, one can
also provide a refresh token. This token will be used to extend the validity period of the token
to generate a new one later, without having to force the user to resend their login data
of the session.

El token de refresco se utiliza opcionalmente, por lo que no todas las implementaciones deben controlarlo
necessarily.

JSON Web Token

The provided text is a URL and does not contain translatable content. Page 15 of 27
API Development Manual

One of the standards for producing tokens on the server side is JSON Web Token. Basically
specify a whole operation that must be implemented on the server side to produce such tokens and
verify its validity when necessary.

The JSON Web Token standard indicates that server-side tokens are created using a string of
text encrypted by a key, which is kept secret on the server side. That same key must be
use to decrypt the token and verify its validity.

The token itself, once decrypted, allows for knowledge about the user who made the request.
that is to say, it is a way to maintain session data and know things about the user, such as their email, name, or
any other information that the application deems necessary.

Note: The session, which is a fundamental part of server-side applications, is problematic.


for storage in distributed systems (for example in services that operate through
load balancing). For that reason, in JSON Web Token it is expected that the session is stored in the
client, as described above. To clarify possible doubts for those coming from the
traditional backend programming, in this token authentication model also includes
some session data, only that the session in this case is stored on the client and not on the server. The
The client is the one who sends the session data to the server with each access that requires authorization.

Libraries for JSON Web Token

Depending on the backend technology to be used, we can find different libraries for
to comfortably implement the generation and verification of tokens. There are libraries for all
backend languages and usually the frameworks offer some alternative.

In the specific case of Javascript (relevant because NodeJS is a common platform for implementation
of REST APIs), the creation and verification of the token can be done with the "jsonwebtoken" library, which is
quite simple to use.

Implementation of an authentication and authorization process via JSON Web


Token

In this article, what we were interested in was clarifying a series of concepts, since this process by itself
Authentication and authorization is not trivial. But I'm sure you're interested in having some extra idea that you...
allows the implementation of this usual operational scheme of modern applications.

The process has two fundamental parts for its implementation, which are totally independent.
between them, as they must be approached as two distinct developments, the client side and the server side.

JWT on the server side

As we have said, the implementation mainly depends on the technologies we use on the side.
from the server, so it would be complicated to see them all, however, if you want some code you can take a look
a glance at this article, where it explains ageneric software for creating a REST API from
a JSON, with authorization by JWT.

The provided text is a URL, which does not require translation. Page 16 of 27
API Development Manual

Other implementations, explained step by step and in great detail, can be found in courses of
EscuelaIT. I recommend itRESTful API Course with Laravelor the Development course with NodeJS and
MongoDB.

Client-side implementation of authentication and authorization in an API

To implement the client-side authentication process, we recommend using a framework.


JavaScript. You can learn right here with theAngular Manualor thePolymer 2 Manual, for example.

These two frameworks/libraries are also explained in SchoolIT courses where it is shown step by step the
customer process for authentication and authorization. For example, we recommend you theAngular course
(this is the most recent at the time of writing this text). or theApplication Development Course with
Polymer 2.

This article is the work of Miguel Angel Alvarez.


It was first published on 11/04/2018
Available online atThe provided text is a URL and cannot be translated.

The provided link does not contain any text for translation. Page 17 of 27
API Development Manual

Create a REST API, 5 minutes with json-


server

Create a REST API in 5 minutes, for educational purposes, ideal for learning frontend development with
a client-side Javascript framework, using json-server.

In this article, we will see how we can create a REST API in less than 5 minutes, which we will be able to
use for educational purposes or for prototyping, ideal when we are learning to develop with a
client-side JavaScript framework.

The idea is to achieve a perfectly functional API that supports the typical operations of any API.
Standard REST, offering the typical operations through the different HTTP verbs, but without having
that investing hours of our time to supply it.

In order to be that fast, we will use a simple JSON file as a data source, where we will be able to
generate our data model, with different entities, and test data. As a REST server
we will use a program called 'json-server', developed with NodeJS that offers us the possibility of
to have a web server that responds to typical API operations.

The REST API that we are going to create will be fully functional, that is, it will perform all operations.
possible about our data (readings, modifications, insertions, and deletions), storing the data in
the JSON file. Data persistence is done in the JSON text file itself, in this way,
In future accesses to the web application, the API will remember its state by maintaining all the activity that has taken place.
carried out over time.

At the end of the article, you will also see a video that explains the entire process and shows how to carry it out.
few minutes.

Note: If you are not clear about what REST is, I recommend that you read the article.What is RESTfrom Eduard
Tomàs explains it very well and very quickly. Even if you have an idea of what a REST API is and
If you want to complete the information and learn more details about this type of resources, reading will be very helpful.
good.

The provided text is a URL and does not contain any translatable content. Page 18 of 27
API Development Manual

Download json-server
The first step to having our API is to download and install json-server. This program is a package of
NodeJS that we will install via npm.

Note: If you do not have NodeJS, you will need to install it on your computer. It is very simple by going to
https://nodejs.organd following the installation instructions. We also recommend theManual
from NodeJS at DesarrolloWeb.com, where you will find useful information about 'Node'. The manager of
npm packages are installed automatically during the installation of NodeJS on your machine.

We will execute the following command in our terminal:

npm install -g json-server

The npm package manager will install json-server along with all its dependencies. In the meantime, we can go
taking the following step.

Create a JSON file with the data from our API


In any folder on our computer, we must create the JSON file that will serve as the source of
data for our API. The data will be what we need in our application and in the API itself
JSON can be used to initially introduce a set of test data.

Note: You canlearn more about JSON in this articleIn reality, it is no longer just a text file.
plan, which you will save with UTF-8 encoding. The notation to define the data is done as if
It was a JavaScript object. When working with JSON, a data model definition is not made like
it is done in a relational database, since this data model is defined through the own
data.

We can see a sample data set in the following JSON code, which stores movies and a
set of movie classifications.

"peliculas": [

"id": 1,

The Sixth Sense

M. Night Shyamalan

Drama

},

The provided text is a URL and does not contain translatable content. Page 19 of 27
API Development Manual

"id": 2,

Pulp Fiction

Tarantino

Action

},

"id": 3,

All About My Mother

Almodóvar

Drama

},

"id": 4,

300

Zack Snyder

Action

},

"id": 5,

The Silence of the Lambs

Jonathan Demme

Drama

},

"id": 6,

Forrest Gump

Robert Zemeckis

Comedy

},

"id": 7,

Las Hurdes

Luis Buñuel

Documentary

],

"clasificaciones": [

Drama

"id": 1

},

Comedy

"id": 2

},

Documentary

"id": 3

},

Action

"id": 4

Unable to access the content of the provided URL. Page 20 of 27


API Development Manual

This JSON file will typically have a .json extension. In our case, we could save it as
movies.json

Start the REST API server


As the third and final step to get our API working, we must start the API server, which is
say, our newly installed json-server. We also do this from the terminal, with the following
command.

json-server --watch peliculas.json

We will soon see a series of messages indicating how we could access our
data source, through the server URLs, or the URLs of the resources or entities generated in the
JSON.

Access the API


Now we only have to access the API. You will really be able to enter the 'home' of the json-server.
for your API through a URL like this:

http://localhost:3000

On that page, you will find links to the various resources of your API. If you open them, you will see that it returns data.
JSON like most REST APIs. The operations you can perform on the API are the typical ones and
It operates basically through the HTTP verbs. In fact, it does not differ at all from any other.
API that you can use.

http://desarrolloweb.com/manuales/manual-desarrollo-api.html Page 21 of 27
API Development Manual

In addition, the API is perfectly enabled to be invoked from other domains thanks to being enabled
CORS, or if desired usingJSONP.

In summary, in less than 5 minutes we have a working API that will be perfect for us to carry out
our client-side Javascript programming with access to data from an API. As we have said, this
The JSON server is more focused on educational purposes or also on prototyping a web project or app.
for mobile devices.

A separate object of study would be access to that data, which you will generally do with Ajax, using a
framework likeAngularJSor a library likeBackboneJS, or at least withjQuery.

Video of the creation of the API

Below you can see the entire process of creating the REST API in video.

To view this video, it is necessary to visit the original article at:http://desarrolloweb.com/articles/create-


api-rest-json-server.html

This article is the work of Miguel Angel Alvarez


It was first published on 11/27/2015
Available online atThe provided text is a URL and does not contain translatable content.

Unable to translate the content from the URL provided as it leads to a webpage. Page 22 of 27
API Development Manual

REST API with JWT Authentication with


JSON Server and jsonwebtoken

How to create a REST API in 30 seconds, with JWT (JSON) based authentication functions
Web Token) using JSON Server and jsonwebtoken.

In this article, I will show you how you can create a REST API in less than 10 minutes with
JSON Web Token (JWT) based authentication, with virtually zero configuration, ideal for
prototype single-page frontend applications.

The basis of this project is JSON Server, which we have already had the opportunity to discuss. JSON Server allows
create a REST API from a JSON file that you have on your hard drive, providing a capable server
to receive GET, PUT, DELETE operations, etc. As we have already presented this software in another
On this occasion, we will take it for granted. You can access the previous article where JSON Server is explained.
in greater detail.

The extra we are here to report on this occasion is the authentication system for REST APIs based on
token. JSON Server does not have authentication implemented, so it was not possible with just that.
prototyping applications with restricted parts by login (username and password). Having this is
interesting to be able to develop such an important part in a project as authentication.

Note: To learn more about token authentication, we recommend reading the article
Token authenticationthat addresses many concepts that will clarify this popular model for the
application security.

But the truth is that, as JSON Server is built, it is quite easy to create a system that,
by relying on it, can restrict certain resources of the API, so that they are only available to
correctly authenticated users.

Unable to access or translate the content from the provided URL. Page 23 of 27
API Development Manual

JSON Server and JWT Auth


In this Github project we find everything we need to deploy your REST API in 30
seconds (the time it takes you to type a console command), with built-in JWT authentication from
house. It is a project in which I have several ideas to improve it, but it can be used.
perfectly now.

You can find the repository on GitHub at this link:The provided text is a URL and does not contain any translatable content.
with-jwt-auth

As I mentioned, it basically implements another quite popular open source software called
JSON Server, to which we have added a basic authentication based on JSON Web Token.

Below I leave a translation into Spanish of the README.md file, in which I provide the details for
use the software and to be able to configure it with our own dataset.

Specific instructions for setting up and configuring the REST server with
JWT authentication
Once cloned or downloaded the repository to your local computer, the only thing you need to do to set it up
launch your REST API with authentication by executing the startup file called "index.js".

node index

When we invoke the execution of the index.js file like this, the software starts with the configurations.
defined as defaults.

JSON server starts on port 3000


As a dataset, use the file located at the path: "json-samples/default.json".
Delay of 1500 milliseconds in the response

Startup arguments

You can configure your API server with authentication through arguments in the node call.
index.

--file is used to indicate the path to another json file with the API data.
--port is used to indicate the startup port.
--authentication is used to define whether we want authentication or not.
--delay: indicate the delay time in the response.

For example, this command starts another JSON file as a data model and listens on port 3000.
It also starts with the authentication system working. (See later for the routes that are)
protected and the routes that are free, as well as the routes to log in and create new users.

node index --file=./json-samples/series.json --port=3333

The provided text is a URL and does not contain translatable text. Page 24 of 27
API Development Manual

This second command, apart from setting the path and the port, indicates that authentication is not desired.

node index --file=./json-samples/marcadores.json --port=3333 --authentication=no

Another modification I made to JSON Server that works very well for me to better simulate how
REST APIs work by creating a delay in the response time. So, even if you have
the API working locally, the server will take time to respond as if it were a remote server,
being able to perceive effects like the typical Ajax spinning wheel while waiting for the response.

If you want, you can remove the delay in the response, or set it up differently, you can do it with the
argument "delay", as follows:

node index --file=./json-samples/series.json --delay=0

The delay is measured in milliseconds. So, if you want to indicate the delay time to half a second
could you start with:

node index --delay=500

Routes for the authentication system

The following routes are useful for implementing the authentication flow.

Login: /login
/sign-in
Verify a user: /verify

To use the login and registration routes, "POST" requests must be sent to those routes, indicating the user.
to register or authenticate using a JSON object that we will place in the body of the request. That part the
you will have to do with your preferred Javascript library or framework.

The object that you will place in the body of the request will be something like this:

[email protected]

The user verification route '/verify' is used to check if the token we have for a
supposedly authenticated user is valid. For that check, you will have to send the token from the
client, through the headers of the HTTP request.

application/json

Here_you_place_the_token

The provided text is a URL and does not contain translatable content. Page 25 of 27
API Development Manual

Note: In this commented version of this authentication system, user data is stored.
simply in the memory of Node. Therefore, with any server restart, all users are
they lose.

To facilitate the workflow, when the REST API server starts, a user is created directly.
in the memory, which you can use for your tests, without having to register.

[email protected]
1234

In addition, if you have a basic knowledge of Javascript and NodeJS, you could edit the index.js file to
configure this user with other data, or add other users to the setup that will be created automatically
when the server restarts.

Protected routes and public routes

So that in your applications you can play with different types of routes, both public and
restricted, we have implemented this program by placing routes that do not require authorization. The criterion that
the following has been followed:

All GET type routes to the REST API are considered public routes, where verification is not performed.
that there is a correctly authenticated user.
All other HTTP methods (POST, PUT, DELETE...) are behind authenticated routes.
for which the user verification process is carried out.

To verify the user on an authenticated route, the same process is followed as described on the route.
/verify. That is, you have to send the valid authentication token in the HTTP headers. In case
if the token is not sent, or it is incorrect or expired, the server will respond with an error
401.

The token is sent in the headers, in a way like this:

application/json

Put_here_the_token

I hope that with these notes you can create your own REST API system with JWT authentication.
agile way and you can develop your frontend project with a standard and extremely easy server
configure.

This article is the work of Miguel Angel Alvarez


It was first published on 20/03/2018
Available online atUnable to access the content of the provided URL for translation.

Unable to access or translate content from URLs. Page 26 of 27


API Development Manual

http://desarrolloweb.com/manuales/manual-desarrollo-api.html Page 27 of 27

You might also like