Cómo consumir automáticamente APIs con React

Rate this content
Bookmark

En esta charla, presentaré a la audiencia el potencial de OpenAPI para simplificar y mejorar el proceso de desarrollo para las aplicaciones React. Demostraré cómo OpenAPI puede ser aprovechado para autogenerar automáticamente APIs REST, optimizando la consumición de datos dentro de los proyectos React. Con un enfoque agudo en la eficiencia y la fiabilidad, los asistentes obtendrán valiosos conocimientos sobre la implementación de pruebas automatizadas para garantizar la robustez y la calidad en sus aplicaciones.

Theodore Vorillas
Theodore Vorillas
7 min
08 Dec, 2023

Video Summary and Transcription

La charla de hoy cubre los desafíos de desarrollar APIs y las herramientas disponibles para simplificar el proceso. También demuestra la construcción de una aplicación de menú de pizza utilizando React y Fastify, con documentación y generación de SDK utilizando Swagger y OpenAPI. Orval se introduce como una herramienta para generar mutaciones, pruebas con mocks generados por trabajadores de servicio simulado, y utilizando Zod para la validación. Admite múltiples lenguajes y marcos, y permite consumir APIs de varios recursos. El SDK se puede rastrear utilizando control de versiones, y las especificaciones de Open API pueden generar Swagger UI y Redux doc asserts.

Available in English

1. Introducción a las APIs y sus Desafíos

Short description:

Hoy, voy a hablar sobre los desafíos de desarrollar APIs y las herramientas disponibles para facilitarlo.

OK, así que solo tenemos cinco minutos, así que voy a llevarlo como si lo hubiera robado. Mi nombre es Teodor, soy un ingeniero de software con sede en Atenas, Grecia, trabajo para Proxima Analytics, que es una plataforma de análisis de código abierto ética. Y hoy voy a hacer otra charla sobre APIs. Y puedo decirte que durante mi carrera he desarrollado tantas APIs. Y realmente puedo decirte que desarrollar APIs es bastante difícil. Tienes que pensar en cambios de código, documentación, romper cosas, seguridad de tipo, como consumir desde diferentes clientes o diferentes aplicaciones y así sucesivamente. Y hay herramientas por ahí, como GraphQL Cogent, ERPC, lo que sea, que pueden generar SDKs de forma semi-automática para consumirlos en tus aplicaciones. Pero eso puede ser un poco complicado y puede estar realmente acoplado con el marco que estamos usando actualmente.

2. Construyendo una Sencilla Aplicación de Menú de Pizza

Short description:

Hoy, vamos a construir una sencilla aplicación de menú de pizza utilizando React y Fastify. Usaremos Swagger y OpenAPI para documentar nuestras APIs y generar SDKs. La interfaz de usuario de Fastify React proporciona documentación completa y capacidades de prueba. Para generar nuestro SDK, utilizaremos Orval, que admite diferentes marcos y bibliotecas de búsqueda. Podemos listar y crear elementos del menú de pizza fácilmente.

Así que hoy vamos a intentar algo sencillo, en menos de cinco minutos, vamos a intentar construir una sencilla aplicación de menú de pizza. Vamos a utilizar React y Fastify, React obviamente, y Fastify como servidor. Y como siempre, la seguridad de tipo es imprescindible. Así que vamos a empezar rápidamente con esto.

Tenemos una configuración realmente básica sobre nuestro servidor, tenemos un tipo que identifica qué es realmente una pizza, como con un ID y un nombre, y luego podemos exponer dos puntos finales, uno para listar todas las pizzas en el menú, y otro para crear un nuevo elemento de pizza en el menú. Y para documentar nuestra API y empezar a generar nuestros SDKs, vamos a utilizar dos herramientas.

La primera se llama Swagger, que es una forma de documentar APIs RESTful, y encima de eso vamos a utilizar OpenAPI, que es en realidad una especificación para hacerlo. Trabajan con diferentes marcos, diferentes lenguajes, tienen demasiados clientes que también puedes consumir. Y para hacerlo, vamos a instalar dos paquetes para nuestro servidor Fastify, el primero es el módulo Swagger de Fastify, y el otro es la interfaz de usuario que queremos traer arriba.

Para iniciar estos dos módulos, la configuración es bastante básica, así que primero necesitamos incluir los módulos en nuestro servidor, añadir algunas especificaciones sobre las APIs, como una descripción, y luego en la última línea vamos a tomar la salida del módulo Swagger y escribirla en nuestro sistema de archivos. Así que vamos a empezar a describir nuestras APIs.

Primero, tenemos un ID, que es único en toda nuestra base de código, y luego vamos a utilizar etiquetas. Podemos usar etiquetas para separar diferentes recursos, APIs, y así sucesivamente. Y para describir nuestra API, tenemos que describir realmente sólo la respuesta, porque no tenemos parámetros ni parámetros de consulta, y así sucesivamente. Así que nuestra respuesta es un objeto, y estamos devolviendo una matriz de dos elementos de menú de pizza, que tienen un ID y un nombre también. Y por último, pero no menos importante, tenemos que incluir el esquema en nuestra ruta en nuestro servidor Fastify.

De manera similar, vamos a hacer lo mismo para el punto final de creación, pero esta vez tenemos que proporcionar realmente un parámetro, que es el nombre del elemento de pizza. De manera similar, la respuesta devuelve ese ID al cliente. De la misma manera, vamos a adjuntar el esquema a nuestra ruta.

Una vez que tenemos todo listo, esta es la interfaz de usuario de Fastify React, donde puedes tener la completa documentación sobre cada punto final. Realmente tienes valores predeterminados inteligentes allí. Puedes probar la API en el navegador, y así sucesivamente. Pero podrías estar preguntándote dónde entra React en esa ecuación, ¿verdad?

Para generar nuestro SDK, vamos a utilizar Orval. Orval es una herramienta de código abierto que toma la especificación OpenAVI y genera el cliente SDK. Funciona con diferentes marcos como Svelte, Vue, con diferentes bibliotecas de búsqueda como SWR, y React Query también. Tenemos que instalar, globalmente o dentro de nuestro proyecto, el SDK de Orval, y luego vamos a ejecutar el CLI de Orval utilizando la especificación OpenAVI como entrada, y luego apuntando a donde queremos que se genere nuestro cliente.

Para listar... Y este es un componente bastante simple que realmente lista todo, lista todos los elementos del menú de pizza. Como puedes ver, la primera línea es realmente lo que generó Orval. Y de manera similar, podemos crear un formulario realmente simple.

3. Orval: Mutaciones, Pruebas y Documentación

Short description:

Orval genera mutaciones y proporciona pruebas fáciles con simulacros generados por el trabajador de servicio de simulacro. Puedes usar Zod para una validación uniforme tanto en el backend como en el frontend. Hay implementaciones para diferentes lenguajes y marcos. Puedes consumir APIs de varios recursos, incluyendo los disponibles públicamente. El SDK se puede comprometer con el sistema de control de fuente para rastrear cambios. Las especificaciones de Open API se pueden utilizar para generar documentos con Swagger UI y Redux doc asserts. El código está disponible en mi perfil de GitHub.

Tenemos una mutación allí. Así que Orval genera la mutación, y también podemos consumirla dentro de nuestros componentes. Y podrías estar preguntándote acerca de las testing. Orval también toma eso en cuenta.

Así que, de serie, tenemos simulacros generados por el trabajador de servicio de simulacro. Así que es bastante fácil probar todo lo que necesitamos. Y hay más que puedes hacer, porque todo es uniforme. Puedes usar Zod, por ejemplo, para proporcionar una validation uniforme en tu back-end y también en el front-end.

No tienes que quedarte con Fastify, así que puedes usar Rails o Next.js o Express, tú eliges. Así que hay implementaciones en el ecosystem para muchos lenguajes y frameworks. Puedes consumir APIs de diferentes recursos, incluso APIs públicas disponibles. Como todo se compromete, el SDK se compromete con nuestro sistema de control de fuente, todo está en su lugar para que podamos rastrear los cambios y así sucesivamente. Y por último, pero no menos importante, puedes tomar esa especificación de Open API y generar tus propios documentos y demás utilizando la interfaz de usuario de Swagger y Redux doc asserts y demás. El código está disponible públicamente en mi perfil de GitHub, así que no dudes en echarle un vistazo, ver cómo funciona, tal vez darme algunos comentarios y demás. Muchas gracias por tu tiempo y paciencia.

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
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.
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
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.
Handling Breaking Changes in GraphQL
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.
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
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.
Safely Handling Dynamic Data with TypeScript
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!
APIs are Evolving. Again.
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

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.
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
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.
Building GraphQL APIs With The Neo4j GraphQL Library
GraphQL Galaxy 2021GraphQL Galaxy 2021
175 min
Building GraphQL APIs With The Neo4j GraphQL Library
WorkshopFree
William Lyon
William Lyon
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