DEV Community

HarmonyOS
HarmonyOS

Posted on

Get Data from API with RCP in HarmonyOS Next

Read the original article:Get Data from API with RCP in HarmonyOS Next

Photo by Marvin Meyer on Unsplash

Introduction

Hello everyone 😊

In this article, we will cover how we get data from the Google Books API with RCP (Remote Communication Kit) in HarmonyOS Next.

What is RCP?

This module provides the HTTP data request capability. With this capability, your app can send data requests using HTTP. Common HTTP methods include GET, POST, HEAD, PUT, DELETE, PATCH, and OPTIONS.

Let’s make an example about the RCP. Get data from the Google Books API and show this data on the screen.

🔅Let’s create models.

BookModel.ets

export default interface BookModel {
  title: string;
  pageCount: number;
  image: string;
  description: string;
  categories: [];
}
Enter fullscreen mode Exit fullscreen mode

ImagesModel.ets

export interface ImagesModel {
  smallThumbnail: string
}
Enter fullscreen mode Exit fullscreen mode

RSPModel.ets

import { volModel } from './volModel';

export interface RSPModel {
  items: volModel[]
}
Enter fullscreen mode Exit fullscreen mode

volModel.ets

import { VolumeInfoModel } from './VolumeInfoModel';

export interface volModel {
  volumeInfo: VolumeInfoModel
}
Enter fullscreen mode Exit fullscreen mode

VolumeInfoModel.ets

import { ImagesModel } from './ImagesModel';

export interface VolumeInfoModel {
  title: string
  pageCount: number
  imageLinks: ImagesModel
  description:string
  categories:[]
}
Enter fullscreen mode Exit fullscreen mode

🔅 Create constants.

Constants.ets

export const BASE_URL = 'https://www.googleapis.com/books/v1/'

export const url =
  'https://www.googleapis.com/books/v1/volumes?q=apivolumes?q=api&fields=items(volumeInfo/title,volumeInfo/pageCount,volumeInfo/imageLinks/smallThumbnail,volumeInfo/description,volumeInfo/categories)'

Enter fullscreen mode Exit fullscreen mode

🔅 This function initiates a session with RCP, sends the request, processes the response, and closes the session.

RCP.ets

import { rcp } from '@kit.RemoteCommunicationKit';
import { BASE_URL } from './Constants';


function sessionConfig(): rcp.SessionConfiguration {
  return {
    baseAddress: BASE_URL
  }
}

export function getHttp(url: string) {
  const session = rcp.createSession(sessionConfig());
  return session.get(`${url}`).then((res) => res.toJSON()).finally(() => {
    session.close();
  });
}
Enter fullscreen mode Exit fullscreen mode

🔅 Create a view model and get books here.

BookViewModel.ets

import BookModel from '../model/BookModel';
import { RSPModel } from '../model/RSPModel';
import { volModel } from '../model/volModel';
import { getHttp } from '../utils/RCP';
import { url } from '../utils/Constants';

@Observed
export class BookViewModel {
  private static _instance: BookViewModel;
  allBooks: BookModel[] = []

  private constructor() {
  }

  public static get instance(): BookViewModel {
    if (!BookViewModel._instance) {
      BookViewModel._instance = new BookViewModel();
    }
    return BookViewModel._instance;
  }

  async getBooks() {
    const response = await getHttp(url) ?? []
    const rsp = response as RSPModel
    this.allBooks = rsp.items.map<BookModel>((i: volModel) => {
      return {
        title: i.volumeInfo.title,
        pageCount: i.volumeInfo.pageCount,
        image: i.volumeInfo.imageLinks.smallThumbnail,
        description: i.volumeInfo.description,
        categories: i.volumeInfo.categories
      }
    })
    console.info('getBooks', JSON.stringify(this.allBooks, null, 3))
  }
}
Enter fullscreen mode Exit fullscreen mode

🔅 Create a card component for the books.

BookCardComponent.ets

@Component
export struct BookCardComponent {
  @Prop title: string
  @Prop pageCount: number
  @Prop image: string
  @Prop categories: Array<string>

  build() {
    Column() {
      Image(this.image).width(60).height(70).padding({ bottom: 3 })
      Text(this.categories.join(', ')).fontSize(9).fontColor(Color.White).padding({ bottom: 3 })
      Text(this.title).fontSize(11).fontColor(Color.White).padding({ bottom: 3 })
      Text(this.pageCount.toString() + ' pages').fontSize(9).fontColor(Color.White)
    }.padding(2).width('70%').borderRadius(20)
  }
}
Enter fullscreen mode Exit fullscreen mode

🔅 Show the books on the Books Page.

BooksPage.ets

import { BookCardComponent } from '../component/BookCardComponent'
import { BookViewModel } from '../viewmodel/BookViewModel';
import BookModel from '../model/BookModel';

@Entry
@Component
struct HomePage {
  scroller: Scroller = new Scroller()
  @State viewModel: BookViewModel = BookViewModel.instance;

  // get  books when open the page
  aboutToAppear() {
    this.viewModel.getBooks()
  }

  build() {

    Column() {
      Text($r('app.string.books'))

      Scroll(this.scroller) {
        Column() {
          ForEach(this.viewModel.allBooks, (book: BookModel, index: number) => {
            BookCardComponent({
              image: book.image,
              title: book.title,
              pageCount: book.pageCount,
              categories: book.categories
            }).padding({ bottom: 4 })
            Divider().height(2).color(0xCCCCCC).padding({ left: 40, right: 40, bottom: 10 });
          }, (item: string, index: number) => item)
        }.padding({ bottom: 25 })
      }.width('100%').height('100%')
    }.backgroundColor(Color.Black).padding({ top: 10, bottom: 10 }).width('100%').height('100%')

  }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Conclusion

In this article, we demonstrated how to fetch data from the Google Books API using Huawei’s Remote Communication Kit (RCP) in an ArkTS-based HarmonyOS Next project. By integrating RCP with a clean ViewModel architecture, we were able to structure our network requests efficiently and transform the API responses into a usable data model.

References

https://developer.huawei.com/consumer/en/doc/harmonyos-references/remote-communication-rcp?source=post_page-----3bd45d03a5c3---------------------------------------

Written by Merve Yonetci

Top comments (0)