Javascript and APIs¶
Quite often Javascript will need to interact with a backend server where it will send and consume JSON payloads.
Much like PHP, JS can make use of a client library where all of the API communication is handled. This is a separation of concerns and is considered good practice to follow.
Structure¶
When writing your API you should carefully consider the structure you would like.
Generally, your code will consist or request
and response
objects that clearly identify the data required to make
requests and the data that is expected in return.
Without request
and response
objects you will find that it is more difficult to test your code and that new developers to
a project will have to decipher what data is being returned from the server and what data the server expects.
Your API may also need to deal with entities
, these are used on the server side to handle persistence logic but can also
be extended to the frontend. Entities are never returned directly dy an endpoint but usually come as part of a response/request object.
To summarise the above, JS can send request
objects to the server that may contain entities
, JS will receive responses that
may contain entities
that it can manipulate.
For example, in a todo list application, a request
object could be to create
a new todo item, this would contain a todo item entity
.
This also works in reverse where a response
contains a todo item entity
that we can then display in the frontend.
Here is an example directory structure:
.
└── js
└── Data
├── Api
├── Entities
├── Requests
└── Responses
All of the API related logic is placed under the Data
module namespace.
Api
directory contains all of the logic to acceptrequest
objects and in turn returnsresponse
objects.Entities
are the objects used on the server side for persistence logicRequests
are the possible requests that can be sent through different endpointsResponses
are returned from endpoints and contain data from the server
Depending on the size of your project, you may find it easier to group your Api classes based on the entity they are associated with.
For example, if you have a Sales
module with a number of entities and endpoints you would not want this to be grouped under the top
level js
directory. This approach also allows you to split your module into a separate dependency should you find this appropriate.
Should you find you need to restructure things, providing you have not used