Create Designing a new Restful API call authored by Morgan Williams's avatar Morgan Williams
# Designing new RESTful API calls
There are multiple components that go into making a RESTful call. These components are the controller, repository, data source and response/request objects.
---
## Objects
The first piece that should be built are the response and request objects. The request object holds the information that you want to send to the companion app server. This object should also have an `asJSON` that converts the object into a JSON object. The response object holds the information that you plan to receive back from the companion app server. This object should also have a `fromJSON` method that takes in the JSON the server sends back and maps it to the object.
---
## Datasource
The next piece is the datasource. First create an abstract class for the data source that outlines the constructor that takes in the service clients and a method the that will as the command, taking in your request object. This method should return a `Future<Response>`. Then create a class, `datasourceHTTP`, that extends your abstract class and implement your methods. The body of the command function should define the following variables:
- Endpoint – a string the contain the endpoint you want to send it to
- Body – the request object as JSON
- Response – The object returned by the service client request
Finally, convert your response to the response object via its `fromJSON` method and return it.
---
## Repository
If a repository for your feature has not been created already one can be created by first creating an abstract repository class. This class should have the constructor that takes all datasources for the feature, and methods that will be used to call each datasource that return `Future<Result<Response>>`. Next create a `RepositoryHTTP` class that extends your abstract class. Your call functions should make a request to the appropriate `datasource`. If the repository for the feature already exists add your repository to the constructor and add your call function for the abstract class and implemented them as described above.
---
## Controller
If a controller for the feature has not been created already, one can be created by first creating controller class that extends a `StateNotifier<state>`. In the controller file create a state class with the @freezed annotation the holds any data you would like to monitor and a method the create a singleton instance. In the controller classes constructor take in the features repository and state. Create getters for the state’s variables and a method that calls the using the repository then unwraps in from the response class changing with `state.copyWith` as needed. If the controller for the feature already exists simply add the method call.
---
After the controller has been completed the full API call has been complete and should be tested before being called in the view
\ No newline at end of file