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 ;)

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.

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)

- High focus, high abstraction.
- Can be a scaffold to get started quickly and it can be first-class code.
- Greater expressive power.
- Teams can develop in parallel which ultimately gives higher productivity.
- Requires initial additional effort.
Option 2 (Write the code first and design the contract later)

- Not cross-functional, neither team-friendly.
- Coderâs arenât the always best communicators.
- Technical writers donât want to maintain embedded code comments(and you may not want them to.)
- 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 :
- Creating user with given user details and returning unique id generated against that user.
- 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.

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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.