Getting started with API contracts

Ever written API contracts for a Cross-functional team, let me teach you that 😉

API Contracts — Image by the Author

What is an API contract?

API Contract is the documentation of the API. This document is the place where you declare how your API will behave, it includes the endpoints URLs, the actions of each endpoint, arguments, examples of the responses, and any other detail, the development team thinks is interesting to be documented.

There are several file formats that allow you to create a contract and obtain your documentation (or mock server, automated tests, etc.). The most common today is an OpenAPI Specification (formerly known as Swagger).

How does the contract work?

The contract is defined by the providers of the service and destined for the consumers of the API, in other words, for the companies and developers that will use the API. The document is usually created by the development team. If a developer has complete domain knowledge he could be able to compose the documentation alone. Otherwise, he might need the help of some domain expert.

Why Contracts are needed?

Assume that you have been told to build an application, which performs some CRUD operations, and also has a graphical user interface like web, desktop, or mobile application, and you decided to use RESTful architecture to implement the application. Now the first question comes to your mind is where to start? Which one will be the correct starting point? Should I build the backend of the application first? Should I build the client application first and so on.

If you are working alone, it is not as critical as in the case that you work as a group of developers who need to share the implementation of the components which need to be designed.

Teams must be in sync while implementing the corresponding parts of the application itself. Let’s say we have two teams one implementing the client-side, and the other one developing the server-side. Teams must decide on what data will be transferred between both the parties and in what structure the data transferred.

Code-First OR API Code-as-Contract

In the above image, you have been given 2 options, either design the contract first and then write the code OR either write the code first and complete the development and later on design the contract /documentation. What will you do.? Let’s see the pros and cons of both options and then you can decide by yourself which one to go with 😉

Option 1 (Design the contract first and then write the code)

Designing contract first and later on implementation — happy programmer 🙂
  1. High focus, high abstraction.
  2. Can be a scaffold to get started quickly and it can be first-class code.
  3. Greater expressive power.
  4. Teams can develop in parallel which ultimately gives higher productivity.
  5. Requires initial additional effort.

Option 2 (Write the code first and design the contract later)

Going always in the loop because of no proper documentation.
  1. Not cross-functional, neither team-friendly.
  2. Coder’s aren’t the always best communicators.
  3. Technical writers don’t want to maintain embedded code comments(and you may not want them to.)
  4. De-emphasizes API design.

Approaches to OpenAPI Specification(OAS)

When it comes to creating the OAS definition, two important schools of thought have emerged: The “Design First” and the “Code First” approach to API development.

The Design First approach advocates for designing the API’s contract first before writing any code. This is a relatively new approach, but is fast catching on, especially with the use of OpenAPI. In the design-first approach, the API contract acts as the central draft that keeps all your team members aligned on what your API’s objectives are, and how your API’s resources are exposed.

Spotting issues in the design, before writing any code is a much more efficient and streamlined approach than doing so after the implementation is already in place.

Contract First API with Open API Specification

Obviously, the Contract First concept claims that it should be written API’s contract first before writing any code. According to the specification, a contract can be written in YAML or JSON file, and it is both human and machine-readable. This structured file is the definition and structure of your API. By using this definition clients and servers can be generated. Let’s see its advantages along with disadvantages

Advantages of this approach can be listed as:

  • Reusability
  • Development teams does not block each other
  • Good and consistent communication between teams
  • Easy documentation
  • Consistent API models

While having these advantages, it also has the following disadvantages when compared to the code first approach:

  • Slower delivery. Delivery cannot be as fast as in the Code First approach. The reason is that teams should compromise on the specification before the implementation.
  • Maintaining the specification file. Although this is not an obvious disadvantage; for huge projects, the number of specification files may require managing them in another repository. Also, depending on the API models, specification file length makes itself harder to read and maintain.

Prerequisite: SpringBoot framework is being used for the example shown in this article and it is assumed that you have spring boot dependencies in your project.

Let’s make our hands a bit dirty

Assume that we are expected to build an application that does all the basic user operations like :

  1. Creating user with given user details and returning unique id generated against that user.
  2. Deleting user details for a given user id.

We can implement the following endpoints to satisfy application requirements:

/user :

  • POST: Creates a User

/user/{username} :

  • DELETE: delete a user detail with given user_id

Contract Designing :

Considering the above-given requirements, the contract can be something like the following: {project_root}/user-api-spec.json

https://medium.com/media/46c237da0f5e493e48f42a26293351aa/href

Although the definition itself is pretty straightforward, for a further explanation this is a nice resource. and the contract can also be verified and visualized from here.

Model Generation

Our contract is already written. We know the details of our API model. It means that both server and client applications can be built by using this contract.

For the model generation, we will try to create a loosely coupled model as possible, and we will follow the open-closed principle which states that software should be open for extension but closed for modification”; that is, such an entity can allow its behavior to be extended without modifying its source code.

We will create separate models for requests and responses for each operation like creating a user, retrieving a user, updating a user, deleting a user so that later it becomes easy for us to extend it also we will create separate classes for writing business logic, DAO layer for interacting with the database, Controller layer where the client will be interacting with. You can always check out this article, to know the detailed explanation about where to put what data.

For demonstration purposes, we will cover one user operation i.e CreateUser

First of all, add the below two libraries in the build.gradle file.

implementation 'io.springfox:springfox-swagger-ui:2.9.2'
implementation 'io.springfox:springfox-swagger2:2.9.2'

https://medium.com/media/ca1f0d3520599b642037810093170602/hrefhttps://medium.com/media/3a1cd3291929eff67d092deb8a3bc4ed/hrefhttps://medium.com/media/19031b0103aef3367c1e564d2d882e9b/hrefhttps://medium.com/media/5bfff3d43a7b6a304d7a3a9cc9cc438d/hrefhttps://medium.com/media/114761637ac08a5764e4af2defda7e42/href

Now, you can run your project and once the server is up, hit http://localhost:8080/swagger-ui.html#/ in the browser. Now you can test your API’s here. from end to end and now you can remove the mock implementation of the APIs and replace it with actual APIs and yes, don’t forget to inform your client (i.e Front-end) that the actual API is in place now.

Local Host API Testing Via Swagger

You can read more about writing API contracts in a detailed explanation.

I tried to exemplify the Contract-First API Development concept. I hope it would be helpful, and joyful too. Thanks for reading. Happy coding!

You can try this process in your organization and let me know your feedback.

If you liked the article, please do follow me on Twitter || Linkedin for more exciting content, do drop me an email on monishasurana1@gmail.com for working together.


Getting started with API contracts was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by monisha surana

Ever written API contracts for a Cross-functional team, let me teach you that ;)

API Contracts — Image by the Author

What is an API contract?

API Contract is the documentation of the API. This document is the place where you declare how your API will behave, it includes the endpoints URLs, the actions of each endpoint, arguments, examples of the responses, and any other detail, the development team thinks is interesting to be documented.

There are several file formats that allow you to create a contract and obtain your documentation (or mock server, automated tests, etc.). The most common today is an OpenAPI Specification (formerly known as Swagger).

How does the contract work?

The contract is defined by the providers of the service and destined for the consumers of the API, in other words, for the companies and developers that will use the API. The document is usually created by the development team. If a developer has complete domain knowledge he could be able to compose the documentation alone. Otherwise, he might need the help of some domain expert.

Why Contracts are needed?

Assume that you have been told to build an application, which performs some CRUD operations, and also has a graphical user interface like web, desktop, or mobile application, and you decided to use RESTful architecture to implement the application. Now the first question comes to your mind is where to start? Which one will be the correct starting point? Should I build the backend of the application first? Should I build the client application first and so on.

If you are working alone, it is not as critical as in the case that you work as a group of developers who need to share the implementation of the components which need to be designed.

Teams must be in sync while implementing the corresponding parts of the application itself. Let’s say we have two teams one implementing the client-side, and the other one developing the server-side. Teams must decide on what data will be transferred between both the parties and in what structure the data transferred.

Code-First OR API Code-as-Contract

In the above image, you have been given 2 options, either design the contract first and then write the code OR either write the code first and complete the development and later on design the contract /documentation. What will you do.? Let’s see the pros and cons of both options and then you can decide by yourself which one to go with ;)

Option 1 (Design the contract first and then write the code)

Designing contract first and later on implementation — happy programmer :)
  1. High focus, high abstraction.
  2. Can be a scaffold to get started quickly and it can be first-class code.
  3. Greater expressive power.
  4. Teams can develop in parallel which ultimately gives higher productivity.
  5. Requires initial additional effort.

Option 2 (Write the code first and design the contract later)

Going always in the loop because of no proper documentation.
  1. Not cross-functional, neither team-friendly.
  2. Coder’s aren’t the always best communicators.
  3. Technical writers don’t want to maintain embedded code comments(and you may not want them to.)
  4. De-emphasizes API design.

Approaches to OpenAPI Specification(OAS)

When it comes to creating the OAS definition, two important schools of thought have emerged: The “Design First” and the “Code First” approach to API development.

The Design First approach advocates for designing the API’s contract first before writing any code. This is a relatively new approach, but is fast catching on, especially with the use of OpenAPI. In the design-first approach, the API contract acts as the central draft that keeps all your team members aligned on what your API’s objectives are, and how your API’s resources are exposed.

Spotting issues in the design, before writing any code is a much more efficient and streamlined approach than doing so after the implementation is already in place.

Contract First API with Open API Specification

Obviously, the Contract First concept claims that it should be written API’s contract first before writing any code. According to the specification, a contract can be written in YAML or JSON file, and it is both human and machine-readable. This structured file is the definition and structure of your API. By using this definition clients and servers can be generated. Let’s see its advantages along with disadvantages

Advantages of this approach can be listed as:

  • Reusability
  • Development teams does not block each other
  • Good and consistent communication between teams
  • Easy documentation
  • Consistent API models

While having these advantages, it also has the following disadvantages when compared to the code first approach:

  • Slower delivery. Delivery cannot be as fast as in the Code First approach. The reason is that teams should compromise on the specification before the implementation.
  • Maintaining the specification file. Although this is not an obvious disadvantage; for huge projects, the number of specification files may require managing them in another repository. Also, depending on the API models, specification file length makes itself harder to read and maintain.

Prerequisite: SpringBoot framework is being used for the example shown in this article and it is assumed that you have spring boot dependencies in your project.

Let’s make our hands a bit dirty

Assume that we are expected to build an application that does all the basic user operations like :

  1. Creating user with given user details and returning unique id generated against that user.
  2. Deleting user details for a given user id.

We can implement the following endpoints to satisfy application requirements:

/user :

  • POST: Creates a User

/user/{username} :

  • DELETE: delete a user detail with given user_id

Contract Designing :

Considering the above-given requirements, the contract can be something like the following: {project_root}/user-api-spec.json

Although the definition itself is pretty straightforward, for a further explanation this is a nice resource. and the contract can also be verified and visualized from here.

Model Generation

Our contract is already written. We know the details of our API model. It means that both server and client applications can be built by using this contract.

For the model generation, we will try to create a loosely coupled model as possible, and we will follow the open-closed principle which states that software should be open for extension but closed for modification”; that is, such an entity can allow its behavior to be extended without modifying its source code.

We will create separate models for requests and responses for each operation like creating a user, retrieving a user, updating a user, deleting a user so that later it becomes easy for us to extend it also we will create separate classes for writing business logic, DAO layer for interacting with the database, Controller layer where the client will be interacting with. You can always check out this article, to know the detailed explanation about where to put what data.

For demonstration purposes, we will cover one user operation i.e CreateUser

First of all, add the below two libraries in the build.gradle file.

implementation 'io.springfox:springfox-swagger-ui:2.9.2'
implementation 'io.springfox:springfox-swagger2:2.9.2'

Now, you can run your project and once the server is up, hit http://localhost:8080/swagger-ui.html#/ in the browser. Now you can test your API's here. from end to end and now you can remove the mock implementation of the APIs and replace it with actual APIs and yes, don't forget to inform your client (i.e Front-end) that the actual API is in place now.

Local Host API Testing Via Swagger

You can read more about writing API contracts in a detailed explanation.

I tried to exemplify the Contract-First API Development concept. I hope it would be helpful, and joyful too. Thanks for reading. Happy coding!

You can try this process in your organization and let me know your feedback.

If you liked the article, please do follow me on Twitter || Linkedin for more exciting content, do drop me an email on monishasurana1@gmail.com for working together.


Getting started with API contracts was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by monisha surana


Print Share Comment Cite Upload Translate Updates
APA

monisha surana | Sciencx (2021-02-11T05:46:14+00:00) Getting started with API contracts. Retrieved from https://www.scien.cx/2021/02/11/getting-started-with-api-contracts/

MLA
" » Getting started with API contracts." monisha surana | Sciencx - Thursday February 11, 2021, https://www.scien.cx/2021/02/11/getting-started-with-api-contracts/
HARVARD
monisha surana | Sciencx Thursday February 11, 2021 » Getting started with API contracts., viewed ,<https://www.scien.cx/2021/02/11/getting-started-with-api-contracts/>
VANCOUVER
monisha surana | Sciencx - » Getting started with API contracts. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/11/getting-started-with-api-contracts/
CHICAGO
" » Getting started with API contracts." monisha surana | Sciencx - Accessed . https://www.scien.cx/2021/02/11/getting-started-with-api-contracts/
IEEE
" » Getting started with API contracts." monisha surana | Sciencx [Online]. Available: https://www.scien.cx/2021/02/11/getting-started-with-api-contracts/. [Accessed: ]
rf:citation
» Getting started with API contracts | monisha surana | Sciencx | https://www.scien.cx/2021/02/11/getting-started-with-api-contracts/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.