简体   繁体   中英

A question about api design between FE and BE

I'm building a FE-BE app and i came up with some questions about the design of the api between them.

Let's say i'm developing a library application that has 2 screens:

  1. add book {author: string, name: string}
  2. display of the books in the library + the number of copies that exists for each book in all of the libraries in the city

The BE:

  1. stores the new books in the DB
  2. sends a book/list of books to the FE
  3. calls a 3rd party api to get the sum of copies of a book in all of the libraries in the city

So my 2 questions are:

a. when the FE gets books from the BE (GET), each book has id (the id it got when stored in the DB), but when the FE creates a new book and passes it to the BE (POST), it doesn't have any id yet. So should i just put null in the id when passing the new book in the POST request or should I create 2 object types (BookWithId and BookWithoutId)?

b. The number of copies of a book (in all of the city libraries) which is received in the BE via a 3rd party api should be a field in the Book object, so it can be passed to the FE with the book in the GET request, or should the FE request it from the BE through a separate api?

A. Use a DTO (Data Transfer Object) to send the data to the BE, and use a Model class to persist it in the DB. Use a mapper method to map the DTO values to model class and vice versa. So no need to have the ID value in the DTO.

B. Get the books objects from the DB (using the model class), map it to the DTO, get the total number from the 3rd party API and set the value to the DTO and send to FE.

I think you should use two separate DTOs, one for FE->BE communication (createBookDTO) and one for the opposite (queryBookDTO). You can put id property on the queryBookDto object but not in the creation one.

About the second question, you have to think about separation of concerns. FE doesn't need to know that the number of copies is an information coming from a separate service, so make it clean and add the logic to get that information to the BE side. FE can get all the information about a book using a single service, regardless of the origin of the data.

If you'll have this information directly on your DB you'll be able to update your project only on his BE side

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM