APIs are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols. For example, the weather bureau’s software system contains daily weather data. The weather app on your phone “talks” to this system via APIs and shows you daily weather updates on your phone.
APIs are language agnostic (most of the time), which allows the users of the API to be flexible in their technology decisions.
APIs are more broad than just backend and frontend development, so when I refer to API in the future, I’m probably speaking about a backend API service.
REST
What is a REST API?’
A REST API is an API that follows the design principles of the REST architectural style.
REST is short for representational state transfer, and is a set of rules and guidelines about how you should build a web API.
When a client request is made via a RESTful API, it transfers a representation of the state of the resource to the requester or endpoint.
Red Hat
There are alternatives to REST, like GraphQL, but they are hard to secure (see Why, after 6 years, I’m over GraphQL), and don’t offer much more than what an OpenAPI schema does.
REST API in Go
Let’s remove some of the experiments we did previously and get started with the TODO app.
We’ll start by adding some global state (that will eventually be substituted for something else).
Now, let’s add a route to retrieve this state.
Notice the `json:"..."` struct tags, it tells the JsonEncoder what to put as the field name.
We also need to manually set the content type, so that our browser and other clients know what we are sending them.
Now, let’s add a way to add a todo.
To receive input, we create a temporary struct and decode the body of the request into it.
If there was an error decoding or the task was empty, we respond with the status 400: bad requests
To add a delete option, we need a way to indentify the todo, and the task string isn’t enough.
We can add an ID field to the struct and just increment
Let’s also add a way to update a todo.
We, again, create a temporary struct to decode the request’s body into, and then update the todo in the slice.