— Android, build.gradle, dependencies, API, Implementation — 2 min read
When working on an Android project, you may have come across the terms "API" and "Implementation" while adding dependencies to your app's build.gradle
file. These two declarations are used to specify how a dependency should be included in your project, but their difference can sometimes be confusing. In this article, we will explain the difference between these two approaches and provide some guidance on when to use each one.
In general, both api
and implementation
are used to declare dependencies that your Android project needs to compile and run. However, there are some differences between the two:
In simple words, api
makes the dependency available to the entire project, while implementation
keeps it hidden for other modules.
You should use api
when you want to expose the dependency as part of your module's public API. For example, if you are creating a library module that other developers can use, you might want to use api
to make sure that the library's dependencies are also available to anyone who uses it.
1// Example of using API2dependencies {3 api 'com.squareup.retrofit2:retrofit:2.9.0'4}
Here, the Retrofit
library is being added to the project as part of the public API. Any module that uses this library will be able to see the Retrofit
classes and methods.
On the other hand, you should use implementation
when you want to keep the dependency private to a specific module. For instance, if you are creating an Android app that has multiple modules, each with its own dependencies, you would want to use implementation
to ensure that these dependencies do not bleed into other modules.
1// Example of using Implementation2dependencies {3 implementation 'com.squareup.okhttp3:okhttp:4.9.2'4}
Here, the OkHttp
library is being added to the module as a private dependency. Other modules cannot see it or access its classes and methods.
In conclusion, api
and implementation
are both used to declare the dependencies of your Android project, but with different visibility scopes. You should use api
when you want to expose the dependency as part of your module's public API, and use implementation
when you want to keep the dependency private to a specific module. By understanding the difference between these two types of dependencies, you can better manage your project's dependencies and avoid unexpected issues.