How to Automatically Consume APIs with React

Rate this content
Bookmark

In this talk, I'll introduce the audience to the potential of OpenAPI in simplifying and enhancing the development process for React applications. I will demonstrate how OpenAPI can be harnessed to seamlessly autogenerate REST APIs, streamlining the consumption of data within React projects. With a keen focus on efficiency and reliability, attendees will gain valuable insights into implementing automated tests to ensure robustness and quality in their applications.

This talk has been presented at React Day Berlin 2023, check out the latest edition of this React Conference.

Watch video on a separate page

FAQ

The example code is publicly available on Teodor's GitHub profile.

The speaker is Teodor, a software engineer based in Athens, Greece, working for Proxima Analytics.

Proxima Analytics is an ethical open-source analytics platform.

Developing APIs is challenging due to code changes, documentation, breaking changes, type safety, and consumption from different clients or applications.

Teodor mentioned tools like GraphQL, Cogent, and ERPC for semi-automatically generating SDKs.

The simple pizza menu application is built using React for the frontend and Fastify for the backend server.

Swagger and OpenAPI are used for documenting the API, and Orval is used for generating SDKs.

Pizza items are listed via an endpoint that returns an array of pizza items with IDs and names. New pizza items are created via an endpoint that takes the pizza name as a parameter and returns the new pizza item's ID.

Orval is used to generate the SDK client from the OpenAPI specification, making it easier to consume the API in different frameworks.

Orval generates mock service worker-generated mocks out of the box, making it easy to test the API.

Theodore Vorillas
Theodore Vorillas
7 min
08 Dec, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's Talk covers the challenges of developing APIs and the available tools to simplify the process. It also demonstrates building a pizza menu application using React and Fastify, with documentation and SDK generation using Swagger and OpenAPI. Orval is introduced as a tool for generating mutations, testing with mock service worker-generated mocks, and using Zod for validation. It supports multiple languages and frameworks, and allows consuming APIs from various resources. The SDK can be tracked using version control, and Open API specifications can generate Swagger UI and Redux doc asserts.

1. Introduction to APIs and their Challenges

Short description:

Today, I'm going to talk about the challenges of developing APIs and the tools available to make it easier.

OK, so we just have five minutes, so I'm going to drive it like I stole it. My name is Teodor, I'm a software engineer based in Athens, Greece, I'm working for Proxima Analytics, which is an ethical open source analytics platform. And today I'm going to make just another talk about APIs. And I can tell you that during my career I have developed so many APIs. And I can really tell you that developing APIs is pretty damn hard. You have to think about code changes, documentation, breaking stuff, type safety, like consuming them from different clients or different applications and so on. And there are tools out there, like GraphQL Cogent, ERPC, you name it, that they can kind of semi-automatically generate SDKs in order to consume them into your applications. But that can be a bit tricky and it can be really coupled with the framework we are actually using.

2. Building a Simple Pizza Menu Application

Short description:

Today, we're going to build a simple pizza menu application using React and Fastify. We'll use Swagger and OpenAPI to document our APIs and generate SDKs. The Fastify React UI provides full documentation and testing capabilities. To generate our SDK, we'll use Orval, which supports different frameworks and fetching libraries. We can list and create pizza menu items easily.

So today we're going to try something simple, just under five minutes, we're going to try and build a simple pizza menu application. We're going to use React and Fastify, React obviously, and Fastify as a server. And as always, type safety is a must. So let's get this one started quickly.

We have a really basic setup about our server, we have a type that identifies what is actually a pizza, like with an ID and a name, and then we can expose two endpoints, one for listing all the pizzas in the menu, and another one just creating a new pizza item in the menu. And in order to document our API and start generating our SDKs, we are going to use two tools.

The first one is called Swagger, which is a way of documenting RESTful APIs, and on top of that we're going to use the OpenAPI, which is actually a specification to do so. They work with different frameworks, different languages, they have too many clients that you can consume as well. And in order to do so, we are going to install two packages for our Fastify server, the first one is the Fastify Swagger module, and the other one is the UI that we want to bring up.

In order to bootstrap these two modules, the setup is pretty basic, so first we need to include the modules in our server, add some specification about the APIs, like a description, and then on the very last line we're going to take the output from the Swagger module and write it into our file system. So let's start describing our APIs.

First up, we have an ID, which is unique throughout our code base, and then we're going to use tags. We can use tags in order to separate different resources, APIs, and so on. And in order to describe our API, we have to actually describe just the response, because we have no parameters or query parameters, and so on. So our response is an object, and we are returning back an array of two of pizza menu items, which have an ID and a name as well. And last but not least, we have to actually include the schema into our route in our Fastify server.

In a similar manner, we're going to do the same for the creation endpoint, but this time we have to provide actually one parameter, which is the name of the pizza item. In a similar fashion, the response gets back that ID to the client. In the same manner as well, we're going to attach the schema into our route.

Once we have everything ready, this is the Fastify React UI, where you can have the full documentation about every single endpoint. You actually have smart defaults there. You can test the API in the browser, and so on. But you might be asking where React comes into that equation, right?

In order to generate our SDK, we are going to use Orval. Orval is an open source tool that takes up the OpenAVI specification and generates the SDK client. It works with different frameworks like Svelte, Vue, with different fetching libraries like SWR, and React Query as well. We have to install, globally or inside our project, the Orval SDK, and then we're going to run the Orval CLI using the OpenAVI specification as an input, and then targeting where we want our client to get generated.

In order to list... This is a pretty simple component that actually lists everything, lists all the pizza menu items. As you can see, the very first line is actually what got generated by Orval. And in a similar manner, we can create a really simple form.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Get rid of your API schemas with tRPC
React Day Berlin 2022React Day Berlin 2022
29 min
Get rid of your API schemas with tRPC
Today's Talk introduces TRPC, a library that eliminates the need for code generation and provides type safety and better collaboration between front-end and back-end. TRPC is demonstrated in a Next JS application integrated with Prisma, allowing for easy implementation and interaction with the database. The library allows for seamless usage in the client, with automatic procedure renaming and the ability to call methods without generating types. TRPC's client-server interaction is based on HTTP requests and allows for easy debugging and tracing. The library also provides runtime type check and validation using Zod.
Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
GraphQL has made a huge impact in the way we build client applications, websites, and mobile apps. Despite the dominance of resolvers, the GraphQL specification does not mandate their use. Introducing Graphast, a new project that compiles GraphQL operations into execution and output plans, providing advanced optimizations. In GraphFast, instead of resolvers, we have plan resolvers that deal with future data. Graphfast plan resolvers are short and efficient, supporting all features of modern GraphQL.
Handling Breaking Changes in GraphQL
GraphQL Galaxy 2022GraphQL Galaxy 2022
22 min
Handling Breaking Changes in GraphQL
Top Content
This Talk discusses handling breaking changes in a GraphQL schema, including the use of the deprecated directive to tag fields that should no longer be used. It also covers the process of deploying GraphQL APIs and mobile apps, highlighting the challenges of mobile app release adoption. The Talk emphasizes the importance of making safe upgrades in mobile apps and provides strategies for detecting and handling breaking changes, such as using TypeScript and GraphQL Inspector. Overall, the Talk emphasizes the need to minimize user impact when introducing breaking changes in GraphQL schemas.
Advanced Patterns for API Management in Large-Scale React Applications
React Advanced Conference 2021React Advanced Conference 2021
20 min
Advanced Patterns for API Management in Large-Scale React Applications
Top Content
This Talk covers advanced patterns for API management in large-scale React applications. It introduces the concept of an API layer to manage API requests in a more organized and maintainable way. The benefits of using an API layer include improved maintainability, scalability, flexibility, and code reusability. The Talk also explores how to handle API states and statuses in React, and provides examples of canceling requests with Axios and React Query. Additionally, it explains how to use the API layer with React Query for simplified API management.
Safely Handling Dynamic Data with TypeScript
Node Congress 2021Node Congress 2021
29 min
Safely Handling Dynamic Data with TypeScript
Top Content
This Talk discusses the safe handling of dynamic data with TypeScript using JSON Schema and TypeBox. Fastify, a web framework, allows developers to validate incoming data using JSON schema, providing type safety and error handling. TypeBox is a powerful library that allows developers to define JSON schemas and derive static types in TypeScript. The combination of JSON schema, TypeBox, and Fastify provides powerful tools for type safety and validation of dynamic data.
APIs are Evolving. Again.
JSNation 2023JSNation 2023
28 min
APIs are Evolving. Again.
Matteo Collina
Luca Maraschi
2 authors
Technology is a spiral, with foundational ideas resurfacing. Java revolutionized enterprise applications. REST and JSON simplified building APIs and websites. Node.js enabled fast and custom development, leading to the microservices revolution. Platformatic aims to fill the gap in building, managing, and scaling microservices painlessly.

Workshops on related topic

Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
WorkshopFree
Sean Landsman
Sean Landsman
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.
Database Workflows & API Development with Prisma
Node Congress 2022Node Congress 2022
98 min
Database Workflows & API Development with Prisma
WorkshopFree
Nikolas Burk
Nikolas Burk
Prisma is an open-source ORM for Node.js and TypeScript. In this workshop, you’ll learn the fundamental Prisma workflows to model data, perform database migrations and query the database to read and write data. You’ll also learn how Prisma fits into your application stack, building a REST API and a GraphQL API from scratch using SQLite as the database.
Table of contents:
- Setting up Prisma, data modeling & migrations- Exploring Prisma Client to query the database- Building REST API routes with Express- Building a GraphQL API with Apollo Server
Best Practices and Patterns for Managing API Requests and States
React Advanced Conference 2022React Advanced Conference 2022
206 min
Best Practices and Patterns for Managing API Requests and States
Workshop
Thomas Findlay
Thomas Findlay
With the rise of frameworks, such as React, Vue or Angular, the way websites are built changed over the years. Modern applications can be very dynamic and perform multiple API requests to populate a website with fresh content or submit new data to a server. However, this paradigm shift introduced new problems developers need to deal with. When an API request is pending, succeeds, or fails, a user should be presented with meaningful feedback. Other problems can comprise API data caching or syncing the client state with the server. All of these problems require solutions that need to be coded, but these can quickly get out of hand and result in a codebase that is hard to extend and maintain. In this workshop, we will cover how to handle API requests, API states and request cancellation by implementing an API Layer and combining it with React-Query.
Prerequisites: To make the most out of this workshop, you should be familiar with React and Hooks, such as useState, useEffect, etc. If you would like to code along, make sure you have Git, a code editor, Node, and npm installed on your machine.