A Beginner's Introduction to CRUD APIs
Tags: webdev, beginners
Published: 2020-11-17 14:39:48

# Introduction

Modern front-end web frameworks like React, Angular, and Vue are dominating the web development scene. All of these frameworks are client-side, meaning that they do not have access to server resources (ex: calling a database or accessing environment variables).

This creates a need for a separate, back-end application that will provide the front-end framework with necessary information. By far the most popular approach to providing these front-end applications with data is by creating an API.

# How this article will be structured

This article is going to be structured by way of definition. Here are the key terms that we are going to get through

* HTTP
  * GET
  * POST
  * PATCH
  * PUT
  * DELETE
* JSON
* API
* CRUD
* Model

# HTTP
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qfxl7d54r2tioot638uy.jpg)
*HyperText Transfer Protocol.* You can think of HTTP as a spoken language. If my laptop wants to communicate with a webserver, they need to be speaking the same language so that they can understand each other. HTTP is the language that computers use to transfer information between each other.
### HTTP Methods (à La Carte 🍝)
![Alt text](https://images.unsplash.com/photo-1414235077428-338989a2e8c0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80)

<span>Photo by <a href="https://unsplash.com/@jaywennington?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jay Wennington</a> on <a href="https://unsplash.com/s/photos/restaurant?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>

There are five **major** HTTP methods that are used with CRUD APIs. Those methods are: GET, POST, PATCH, PUT, and DELETE. Raf Rasenberg makes a perfect restaurant analogy to understand these methods.
{% twitter 1327888503158546438 %}
#### GET
{% twitter 1327888504744005632 %}
#### POST
{% twitter 1327888506446884865 %}
#### PATCH
{% twitter 1327888508195921920 %}
#### PUT
{% twitter 1327888509752012800 %}
#### DELETE
{% twitter 1327888511131906049 %}
It's important to note that these HTTP methods are purely semantic. However, it is good practice to label your HTTP endpoints with the correct method (especially for a REST API which is very client focused).

# JSON
*JavaScript Object Notation.* JSON is the language of APIs. It is the most popular way to transfer large amounts of data over HTTP.

> JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

Here is an example JSON object that contains all the acceptable JSON data-types:
```JSON
{
    "myString": "Hello String",
    "myNumber": 42,
    "myBoolean": true,
    "myNull": null,
    "myList": ["Hello String", 42, true, null],
    "myObject": {
        "id": 1,
        "description": "A really cool description" 
    }
}
```
JSON is stored in key-value pairs. Each key is a string that is encased in double quotations (`"`). Each pair can be a **string**, **number**, **boolean**, **null**, **list**, or **object.** After every pair, excluding the last pair, there must be a comma to separate the next key-pair value. Notice how the `null` in `"myList"` as well as the pair of `"myObject"` do not end with a comma. That is because they are the last pairs in their collection.

# API
![Alt Text](https://images.unsplash.com/photo-1546561892-65bf811416b9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80)
<span>Photo by <a href="https://unsplash.com/@tommyvkessel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tommy van Kessel 🤙</a> on <a href="https://unsplash.com/s/photos/star-wars?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>

*Application Programming Interface.* An application programming interface allows a programmer to interact with a set of data over HTTP.

Let's say that you are a huge Star Wars fan and you want to set up a Star Wars fan wiki. You would probably want to have a dataset of all the Star Wars characters that your website can interact with. Lucky for you, there is [SWAPI.dev](https://swapi.dev/), a free and publically accessible Star Wars API. Let's see what it can do.

Calling the url [http://swapi.dev/api/people/1](http://swapi.dev/api/people/1) returns the following JSON data:
```JSON
{
    "name": "Luke Skywalker", 
    "height": "172", 
    "mass": "77", 
    "hair_color": "blond", 
    "skin_color": "fair", 
    "eye_color": "blue", 
    "birth_year": "19BBY", 
    "gender": "male", 
    "homeworld": "http://swapi.dev/api/planets/1/", 
    "films": [
        "http://swapi.dev/api/films/1/", 
        "http://swapi.dev/api/films/2/", 
        "http://swapi.dev/api/films/3/", 
        "http://swapi.dev/api/films/6/"
    ], 
    "species": [], 
    "vehicles": [
        "http://swapi.dev/api/vehicles/14/", 
        "http://swapi.dev/api/vehicles/30/"
    ], 
    "starships": [
        "http://swapi.dev/api/starships/12/", 
        "http://swapi.dev/api/starships/22/"
    ], 
    "created": "2014-12-09T13:50:51.644000Z", 
    "edited": "2014-12-20T21:17:56.891000Z", 
    "url": "http://swapi.dev/api/people/1/"
}
```
Awesome! Now you can start building Luke Skywalker's wiki page using the power of APIs!

# CRUD
![Crud](https://www.dorusomcutean.com/wp-content/uploads/2020/03/crud.jpg)
*Create, read, update, delete* CRUD is not a technology nor is it a language. CRUD is a design pattern for constructing web apis. 

Let's say that you've created an API for books. You know that you want a book to contain an `author`, a `title`, a `pageCount`, and an `id.` 

So we've planned out what we want our book to look like and we've made our API. There is only one issue, it's empty! You want to **create** a book object. We create a book with an HTTP POST request.

With our newly created book, it would be reasonable that we would want to see this book's qualities. This is what the **read** part of CRUD is for. We **read** the book's attributes with an HTTP GET request. An example JSON response could look like this:
```JSON
{
    "id": 1,
    "title": "Henry Porter",
    "author": "J.K. Rowling",
    "pageCount": 404,
}
```
Oh no! We made a mistake! We misspelled "Harry Potter" as "Henry Porter." That's not good. We need to change it. This is what the **update** part of CRUD is for. Using an HTTP PUT request, we can **update** the book's title to be "Harry Potter."
```JSON
{
    "id": 1,
    "title": "Harry Potter",
    "author": "J.K. Rowling",
    "pageCount": 404,
}
```

Much better! Finally, we've decided that we don't want Harry Potter to be part of our API anymore. We're more of a Lord of the Rings person anyways. This is what the **delete** part of CRUD is for. We can **delete** Harry Potter from the API using an HTTP DELETE request.
```JSON
{
}
```

# Models
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ogwbccm17y7b24ues8hp.png)
Icons made by <a href="https://www.flaticon.com/authors/flat-icons" title="Flat Icons">Flat Icons</a> from <a href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a>

If you have been programming in a declarative programming language like Java or C, you are probably familiar with classes. When you create a class, you give it attributes and each attribute has a type. If we were making a class for the book in our CRUD section, we would give it `string` attributes for the title and author, and `int` attributes for the page count and the id. This is exactly how we would create a model. We choose attributes for the type of data we want to model and what data types will represent those attributes.

Most models should have some form of validation. If our API received a POST request to create a book that had -1 pages, that'd be pretty suspicious. We would probably want to validate in our book model that the page count is greater than or equal to 1. We also want to make sure that our model doesn't receive any blank values. Creating a book with a `null` title could cause some confusion for the API client. So we validate our book's author and title attributes to ensure that they are not null.

# Wrapping up
After reading this article, you should now have a good idea of what each of these terms is:
* HTTP
  * GET
  * POST
  * PATCH
  * PUT
  * DELETE
* JSON
* API
* CRUD
* Model

Now that we have a grasp of the major terms, we are ready to start programming our own APIs. In the next article, I will walk you through creating your first API using Python. See you then!