It is easy to implement calls to API endpoints, then to parse JSON and handle the data – but what is a good design pattern for this?
Here are some ways I have tried but I feel like there should be a better way:
- Create a singleton class that manages all networking code and all data parsing code for the entire application for all endpoints. Then any controller class can hit the singleton
- Make network endpoint tasks straight from view controllers – using blocks within the view controller to manage responses
Consider an application that can hit an endpoint (GET) to download a list of appointments. Also consider an POST endpoint where you can send new appointments.
Data must be packaged/unpackaged in JSON and errors must be handled appropriately.
What is a good design pattern to accomplish this?
And before you downvote this post and say its too broad or subjective just look at this page:
https://softwareengineering.stackexchange.com/help/dont-ask
Some subjective questions are allowed, but “subjective” does not mean
“anything goes”. All subjective questions are expected to be
constructive.
A good answer to this common problem is hard to find.
1
Treat the REST API as any other data source, and create an abstraction (e.g. AppointmentRepository, etc.) that your controllers use. My examples are in Java, but I think you’ll get the idea.
public interface AppointmentRepository {
Appointment findById(String id) throws RepositoryAccessException;
void create(Appointment appointment) throws RepositoryAccessException;
void update(Appointment appointment) throws RepositoryAccessException;
void delete(Appointment appointment) throws RepositoryAccessException;
}
public class RestAppointmentRepository {
@Override
public Appointment findById(String id) throws RepositoryAccessException {
// make the API call
// translate the JSON to an Appointment object
return appointment;
}
// etc
}
Using an abstraction in this way decouples your controller from the concrete source of data, so the two can change without affecting each other. Consider if in the future the REST API changes its representation of an appointment, which means your mapping code needs to change. When that mapping code is hidden behind an abstraction, there’s no need to make any changes to the controller to handle the REST API change.
This approach also allows you to more easily unit-test your controller without having to worry about the REST API returning data to support your unit tests. In addition to the happy-path test, you should be testing that your controller reacts appropriately when the REST API is unavailable, i.e. when the repository method throws an exception. Take the repository interface as a dependency of the controller, and mock it in your unit test so that you can define its behavior easily.
public AppointmentController extends ViewController {
private final AppointmentRepository appointmentRepository;
public AppointmentController(final AppointmentRepository appointmentRepository) {
Preconditions.checkNotNull(appointmentRepository);
this.appointmentRepository = appointmentRepository;
}
}
...
// unit test
AppointmentController appointmentController = new AppointmentController(mockAppointmentRepository);
1
I would argue that the second method (direct endpoint calls from view controller) is not very future facing because of the possibility of having to extend the functionality to a bulk/automated api call that’s separated from the view.
For example, what if a new requirement came up to post 100,000 appointments via your app, based on an excel input, for which the execution would have to be batched and scheduled to prevent api call limits on your target endpoint? If your calling and handling code was baked into your view controller for a form (define and post a SINGLE appointment), you’d have to extract it into it’s own class (likely singleton), extend it to ensure it can handle the bulk case, and handle responses.
Since the sending of requests is handled by a library, and the JSON parsing of the response is (perhaps?) handled by a library, the crux is determining whether to wrap all call-response logic for all endpoints into one class, or have one for each target system.
Instead of looking at get/post to an appointment api, consider a master CRM system that controls both the creation of an Invoice via ERP integration and entitlement via Product Server integration. In this case, you have two SEPARATE apis being consumed by integration logic, but still utilizing the same library logic to request and parse the response.
My approach has been:
-
Separate all controller (and less importantly, view) logic for each system integration into it’s own namespace within the application. Eg) ERP_Example, PS_Example
-
Abstract the contents (attributes of the request) of the integration call into a (possibly inline) class, then use JSON serialization, controlled by a dedicated, static integration class that is system-specific to make the call, parse the response, and route the success/fail logic appropriately.
Eg) ERP_InvoiceIntegration.class, PR_EntitlementIntegration.class
- Then, when I need to bulkify the calls, I can simply create:
ERP_BatchableInvoiceActioner.class, PR_BatchableEntitlementsActioner.class
to handle the bulk case, and call the integration class from within each batch, knowing that the class itself will correctly route success/fail.
It also seems like this pattern can handle both synchronous and asynchronous api calls, though not as much in the bulk case, depending.
Shorter answer: Singleton for each integration target, but not for each api call (get/post/etc)…