YUHEE1984 / CatsOneday

1 stars 0 forks source link

09 - Your First Spring REST API #9

Closed TheBeege closed 1 month ago

TheBeege commented 2 months ago

Goal

Build your first RESTful API!

Context

First, we're not going to explain what REST is for now. We'll cover that in a later issue. We're going to focus on other concepts: APIs or Application Programming Interfaces (Korean), and MCV or Model View Controller (Korean).

What is an API?

In short, an API is how one program (application) interacts with (interface) another program using software (programming). In web development, we refer to the API as the server software that manages business logic and as the way to interact with that program. Another valid way to think about a web API is that it is the interface to the database where data is stored. In this issue, we won't get into the database, but it's helpful to think about things in this manner.

An API provides some way for other programs to interact with it, usually retrieving or modifying data. The term "API" is actually very broad. In web development, an API often means a server with some HTTP interface. However, API can also mean the functions used to interact with a software library. If we were to use Lombok as an example, the annotations are part of the Lombok API to generate code for you. You write code (programming) to send command to Lombok (interface) for it to generate getters, setters, and constructors for you (application).

Going back to web, an API server usually serves some website or mobile app. Some server that talks to a database (application) provides some way to send commands via HTTP (interface) for other programs to call with code (programming). In this case, the other program is the frontend code or the mobile app code. As a backend engineer, this is your focus. Your job is to provide ways for websites and mobile apps to retrieve and manipulate data.

What is MCV?

Model

A model represents some type of object in your program that users care about. This could be something like an account or a book or a chapter of a book or an author. It's basically something that should be tracked. The model also has some core logic as to how the object should behave. The core of your application logic belongs here.

Controller

The controller is responsible for verifying inputs, handling input and output serialization (formatting), retrieving models, and passing information to and between models. The controller basically coordinates operations between the user input and the models. This is the part that defines the "interface" part of an API.

View

The view is how information from the application is presented to the user. It's the part you see. In API development, this part is usually omitted, or it's considered to be the format of the data that is output.

With all that covered, let's build your first web backend API!

Steps

The Model

  1. In your org.yuhee.catsoneday package, create a new folder/sub-package called cat. This is where your Cat model, controller, and other supporting objects will live.
  2. Move your Cat.java and BreedingSexException.java to this folder.
  3. Don't forget to change the package in those two Java files! Note that if you're using IntelliJ, it may make the change for you.
  4. In your Cat class, create a new public constructor with no arguments.
  5. Remember in #5 how you randomly selected from a list of names for your cats? In this new constructor, do that for name, sex, color, eyeColor, and furPattern.
  6. Again, similarly to how you did in #5, randomly set a reasonable weightInKg, too.

Great job! Technically, your Cat class was already a valid model. I just wanted to add the random initialization to get you some practice and to make it more interesting. Now, let's make this cat available on the server.

The Controller

  1. In your org.yuhee.catsoneday package, create a new class: CatController.
  2. Add an import for org.springframework.web.bind.annotation.RestController, org.springframework.web.bind.annotation.RequestMapping and org.springframework.web.bind.annotation.GetMapping.
  3. Add the @RestController annotation to your CatController class.
    • This tells Spring Boot that this class is an MVC controller for an API, specifically a REST API. Spring will then look to this class for handling certain types of HTTP requests.
  4. Add the following annotation: RequestMapping("/cats").
    • This tells Spring Boot that any requests to your server at the /cats path should use this controller. This means that if your server is on localhost, you could send input to this controller at the URL http://localhost/cats.
  5. Create a new method called getOne (as in get one cat). It should return a Cat model. It needs no parameters.
  6. Add the @GetMapping annotation to your getOne method.
    • Remember the HTTP methods we listed in #7? The Get in GetMapping is referencing the HTTP GET method. This is saying that any HTTP request using the GET method to this controller should execute this getOne method. So GET http://localhost/cats would call this getOne method.
  7. Create a new Cat using the constructor with no arguments.
  8. Return the new cat.
  9. Try running the server with ./gradlew bootRun.
  10. Visit http://localhost:8080/cats. See your new cat! (By default, browsers use the GET HTTP method.)

Congratulations! You've built your first API! It's really simple, just producing a new cat. But it works. But let's do one more thing to make your API a little easier to use for your future frontend engineers 😸

Don't forget to ctrl + c to stop the server!

The Docs

  1. Open up build.gradle.
  2. In the dependencies block, add the following line: implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0'. This adds the SpringDoc OpenAPI starter kit as a dependency.
  3. Run the server again with ./gradlew bootRun.
  4. Visit http://localhost:8080/swagger-ui/index.html. See your API docs!
  5. Click the GET /cats bar.
  6. Click Try it out on the right side.
  7. Click Execute.

Well done! You've now added the Swagger UI for API documentation. This is commonly used to make collaboration between frontend engineers and backend engineers easier. It provides a way for frontend engineers to read about your API and test it without needing to use a terminal or write code.