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.

7 min
08 Dec, 2023

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.

Available in Español

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.

3. Orval: Mutations, Testing, and Documentation

Short description:

Orval generates mutations and provides easy testing with mock service worker-generated mocks. You can use Zod for uniform validation in both backend and frontend. There are implementations for different languages and frameworks. You can consume APIs from various resources, including publicly available ones. The SDK can be committed to the source control system for tracking changes. Open API specifications can be used to generate documents with Swagger UI and Redux doc asserts. The code is available on my GitHub profile.

We have a mutation there. So Orval generates the mutation, and we can consume it inside our components as well. And you might be asking about testing. Orval takes that into the equation as well.

So out of the box, we have mock service worker-generated mocks. So it's pretty fairly easy to test everything as we need so. And there's more that you can actually do, because everything's like uniform. You can use Zod, for example, in order to provide uniform validation in your back-end and the front-end as well.

You don't have to stuck with Fastify, so you can use Rails or Next.js or Express, you name it. So there are like implementations in the ecosystem for so many languages and frameworks. You can actually consume APIs from different resources, even open publicly available APIs. Since everything gets committed, the SDK gets committed to our source control system, everything is in place so we can track down changes and so on. And last but not least, you can actually take that open API specification and generate your own documents and so on using the Swagger UI and Redux doc asserts and so on. The code is publicly available in my GitHub profile, so feel free to jump into, take a look how it works, maybe give me some comments and so on.

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

React Day Berlin 2022React Day Berlin 2022
29 min
Get rid of your API schemas with tRPC
Do you know we can replace API schemas with a lightweight and type-safe library? With tRPC you can easily replace GraphQL or REST with inferred shapes without schemas or code generation. In this talk we will understand the benefit of tRPC and how apply it in a NextJs application. If you want reduce your project complexity you can't miss this talk.
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
Though GraphQL is declarative, resolvers operate field-by-field, layer-by-layer, often resulting in unnecessary work for your business logic even when using techniques such as DataLoader. In this talk, Benjie will introduce his vision for a new general-purpose GraphQL execution strategy whose holistic approach could lead to significant efficiency and scalability gains for all GraphQL APIs.
GraphQL Galaxy 2022GraphQL Galaxy 2022
22 min
Handling Breaking Changes in GraphQL
Top Content
Requirements change, but API contracts are forever - I wish! A breaking change is something that is not backwards compatible. This means that a consumer of your API would not be able to use the new version without making a code change themselves. We avoid breaking changes if possible, but there are cases when they are inevitable. It could be something small: like making a mandatory field optional. Or it could be something big: like removing a query or a mutation. In this talk we'll review the types of breaking changes you may encounter and how to deal with them gracefully.
React Advanced Conference 2021React Advanced Conference 2021
20 min
Advanced Patterns for API Management in Large-Scale React Applications
Top Content
In this talk, you will discover how to manage async operations and request cancellation implementing a maintainable and scalable API layer and enhancing it with de-coupled cancellation logic. You will also learn how to handle different API states in a clean and flexible manner.
Node Congress 2021Node Congress 2021
29 min
Safely Handling Dynamic Data with TypeScript
TypeScript makes JavaScript safer adding static type definitions. Static definitions are wonderful; they prevent developers from making trivial mistakes ensuring every assignment and invocation is done correctly. A variable typed as a string cannot be assigned a number, and a function expecting three arguments cannot be called with only two. These definitions only exist at build time though; the code that is eventually executed is just JavaScript. But what about the response from an API request? In this talk Ethan Arrowood, Software Engineer 2 @ Microsoft, he will cover various solutions for safely typing dynamic data in TypeScript applications. This talk features popular technologies such as Fastify, JSON Schema, Node.js, and more!
JSNation 2023JSNation 2023
28 min
APIs are Evolving. Again.
As developers we stand on the shoulders of giants, and it can be helpful to take a look at the past to gain a better perspective. In this talk we’ll briefly explore the past decade of backend development and architectural patterns.
We’ve often ditched technologies in an attempt to make the developer experience frictionless. However we sometimes forget what we can learn from “the good old days”.
What are you building: a monolith, a microservices system or something in between? A shift in how we see things can help us keep moving forwards.

Workshops on related topic

GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
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.
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
WorkshopFree
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
Node Congress 2022Node Congress 2022
98 min
Database Workflows & API Development with Prisma
WorkshopFree
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
React Advanced Conference 2022React Advanced Conference 2022
206 min
Best Practices and Patterns for Managing API Requests and States
Workshop
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.
GraphQL Galaxy 2021GraphQL Galaxy 2021
175 min
Building GraphQL APIs With The Neo4j GraphQL Library
WorkshopFree
This workshop will explore how to build GraphQL APIs backed Neo4j, a native graph database. The Neo4j GraphQL Library allows developers to quickly design and implement fully functional GraphQL APIs without writing any resolvers. This workshop will show how to use the Neo4j GraphQL Library to build a Node.js GraphQL API, including adding custom logic and authorization rules.

Table of contents:
- Overview of GraphQL and building GraphQL APIs
- Building Node.js GraphQL APIs backed a native graph database using the Neo4j GraphQL Library
- Adding custom logic to our GraphQL API using the @cypher schema directive and custom resolvers
- Adding authentication and authorization rules to our GraphQL API