Saltar al contenido

¿Cómo desarrollar una API de manera eficiente?

Aprende algunos consejos sobre cómo crear tu API de manera eficiente y lidiar con el trabajo real simultáneamente.

Foto de Edho Pratama en Unsplash

Al crear una API para exponer una capacidad o integrar diferentes sistemas, hay principalmente dos formas de hacerlo: enfoque de Contrato-Primero o enfoque de Contrato-Último. La diferencia radica en la metodología que seguirás para crear la API.

En un enfoque de contrato-primero, la definición del contrato es el punto de partida. No importa qué lenguaje o tecnología estés utilizando. Esta realidad ha sido la misma desde el comienzo del sistema distribuido en tiempos de RMI y CORBA y continúa siendo la misma en los tiempos extraordinarios de gRPC y GraphQL.

Comienzas con la definición del contrato entre ambas partes: la que expone la capacidad y el consumidor inicial de la información. Eso implica la definición de varios aspectos de él:

  • Propósito de las operaciones.
  • Campos que tiene cada operación.
  • Información de retorno dependiendo de cada escenario.
  • Información de errores reportados, y así sucesivamente.

Después de eso, comenzarás a diseñar la API en sí y la implementación para cumplir con la definición acordada entre las partes.

Este enfoque tiene varias ventajas y desventajas, pero hoy en día es la forma más «aceptable» de desarrollar API. Como ventajas podemos comentar las siguientes:

  • Reducción de Actividades de Retrabajo: Al comenzar definiendo el contrato, puedes validar rápidamente que todas las partes están de acuerdo con el contrato antes de escribir cualquier trabajo de implementación. Eso evitaría cualquier actividad de recodificación o retrabajo debido a un malentendido o simplemente adaptación de las expectativas y se volvería más eficiente.
  • Separación de Funciones: También proporcionará la separación de funciones para ambas partes, el proveedor y los consumidores. Porque tan pronto como tengas el contrato, ambos equipos pueden comenzar a trabajar en eso. Incluso puedes proporcionar un simulacro para que el consumidor pruebe cualquier escenario rápidamente sin la necesidad de esperar a que se cree el servicio real.

Pero el enfoque de Contrato-Primero tiene algunos requisitos o suposiciones para tener éxito que no son muy fáciles de cumplir en un escenario del mundo real. Esta situación es esperada. Hay muchas metodologías, consejos o recomendaciones que aprendes cuando estás estudiando que no son aplicables en la vida real. Para validar ese comentario, permíteme hacerte una pregunta:

¿Creaste una API y la interfaz que creaste fue 100% la misma que tenías al final?

La respuesta a esa pregunta en mi caso es «No, nunca». Y puedes pensar que soy un mal diseñador de API, y podrías tener razón. Estoy seguro de que la mayoría de las personas que leen este artículo definirían sus contratos mucho mejor que yo, pero ese no es el punto. Porque cuando estamos en la fase de implementación, generalmente detectamos algo que no pensamos en la fase de diseño, o cuando intentamos hacer un diseño de bajo nivel, hay otros conceptos que no contemplamos en el punto que hace que otra solución sea la más adecuada para el escenario, por lo que impactarás la API, y eso tiene un costo.

Es posible que mitiges ese riesgo simplemente dedicando más tiempo a la fase de definición del contrato para asegurarte de que nada esté bien considerado o incluso crear algunos prototipos para garantizar que la API generada sea la final. Pero si haces esto, solo estás reduciendo la probabilidad de que esto suceda, nunca eliminándola, y al mismo tiempo, estás reduciendo los beneficios del enfoque.

Uno de los puntos críticos que comentamos anteriormente fue la eficiencia. Supongamos que pensamos en la eficiencia ahora cuando dedicarás más tiempo a esa fase. Eso significa que será menos eficiente. También comentamos sobre lo grandioso de hacer la separación de funciones: pero en este caso, mientras se extiende el tiempo de creación de la interfaz, también se extiende el tiempo que ambos equipos necesitan esperar hasta que puedan trabajar en sus partes.

Pero implementar el otro enfoque no proporcionará mucho beneficio. Puede llevar a un trabajo aún más costoso porque no obtendrás validación para el cliente hasta que la API esté implementada. Y nuevamente, otra pregunta:

¿Alguna vez compartiste algo con tu cliente por primera vez y no pidieron ningún cambio?

Nuevamente, la respuesta es la misma: «No, nunca». Y ese costo siempre será mayor que el que se habla del cambio en la definición, porque como sabes, el cambio es mucho más costoso cuanto más tarde lo detectes en el ciclo de desarrollo, y no es un aumento lineal. Es mucho más cercano a un aumento exponencial.

Entonces, ¿cuál es mi recomendación aquí? Sigue el enfoque de contrato-primero y acepta la vida real. Así que haz tu mejor esfuerzo para definir la API y tener un acuerdo entre las partes y si detectas algo que pueda impactar la API, notifícalo lo antes posible a las partes. Al final, esto no es más que un enfoque interactivo también para la definición de la API, y no hay nada de malo en ello.

Seamos honestos, no hay una bala de plata que proporcione el camino verde en tu trabajo diario, y eso es lo grandioso de hacerlo y por qué lo disfrutamos tanto. Porque en cada una de nuestras decisiones de trabajo, como sucede en cualquier otro aspecto de la vida, hay tantos aspectos, tantas situaciones, tantos detalles que siempre impactan la increíble y hermosa metodología que puedes ver en un artículo, un documento, una clase o un tweet.

Etiquetas:

How To Develop API Efficiently?

Learn some tips about efficiently creating your API and dealing with the actual work simultaneously.

Photo by Edho Pratama on Unsplash

When creating an API to expose a capability or integrate different systems, there are mainly two ways to do it: Contract-first or Contract-Last approach. The difference is about the methodology you will follow to create the API.

In a contract-first approach, the definition of the contract is the starting point. It does not matter which language or technology you are using. This reality has been the same since the beginning of the distributed system in times of RMI and CORBA and continues to be the same in the extraordinary times of gRPC and GraphQL.

You start with the definition of the contract between both parties: the one that exposes the capability and the initial consumer of the information. That implies the definition of several aspects of it:

  • Purpose of the operations.
  • Fields that each operation has.
  • Return information depending on each scenario.
  • Error information reported, and so on.

After that, you will start to design the API itself and the implementation to meet the definition agreed between the parties.

This approach has several advantages and disadvantages, but today it is the most “acceptable” way of developing API. As advantages we can comment about the following ones:

  • Reducing Rework Activities: As you start defining the contract, you can quickly validate that all parties are OK with the contract before writing any implementation work. That would avoid any re-coding activity or re-work because of a misunderstanding or just adaption of the expectations and become more efficient.
  • Separation of Duties: It will also provide the separation of duties for both parties, the provider and the consumers. Because as soon as you have the contract, both teams can start working on that. Even you can provide a mock for the consumer to test any scenario quickly without the need to wait for the actual service to be created.

But the contract First approach has some requirements or assumptions to be successful that are not very easy to meet in a real-world scenario. This situation is expected. There are a lot of methodologies, tips, or advices that you learn when you are studying that are not applicable in real-life. To validate that comment, let me ask you a question:

Did you create an API and the interface you created was 100% the same one you had at the end?

The answer to that question in my case is “No, never.” And you can think that I am a lousy API designer, and you can be right. I am sure that most people reading this article would define their contracts much better than I do, but this is not the point. Because when we are on the implementation phase, we usually detect something that we didn’t think about in the design phase, or when we try to do a low-level design, there are other concepts that we did not contemplate at the point that makes another solution the best suited for the scenario so that you will impact the API, and that has a cost.

It can be possible that you mitigate that risk by just spending more time on the contract definition phase to make sure that nothing is well-considered or even create some prototypes to ensure that the API generated will be the final one. But if you do this, you are just lowering the probability for this to happen, never removing it, and at the same time, you are reducing the benefits of the approach.

One of the critical points we commented on above was efficiency. Suppose we think about the efficiency now when you will spend more time on that phase. That means that it will be less efficient. Also, we commented on the great thing of doing separation of Duties: but in this case, while the interface creation time is extended, it is also extended the time that both teams need to wait until they can work on their parts.

But implementing the other approach will not provide much benefit. It can lead to even more expensive work because you will get no validation for the customer until the API is implemented. And again, another question:

Did you ever share something with your customer for the first time and they didn’t ask for any change?

Again, the answer is the same: “No, never.” And that cost will always be higher than the one talking about the change in the definition, because as you know, the change is much more costly the further you detect it in the development cycle, and it is not a linear increase. It is much more close to an exponential rise.

So, what is my recommendation here? Follow the contract-first approach and accept real life. So do your best shot of defining the API and have an agreement between parties and if you detect something that can impact the API, notify it as soon as possible to the parties. In the end, this is nothing else than an interactive approach also for the API definition, and there is nothing wrong with it.

Let’s be honest there is no silver bullet that will provide the green path in your daily work, and that is the great thing about doing it and why we enjoyed it so much. Because in each of our work decision as it happens in any other aspect of life, there is so many aspects, so many situations, so many details that always impacts the awesome beautiful methodology that you can see in an article, a paper, a class, or a tweet.

Etiquetas:

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *