Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Weather App (2015) Networking Making an HTTP GET Request with OkHttp

Carlos Monteiro
PLUS
Carlos Monteiro
Courses Plus Student 4,758 Points

What is the best practice to safeguard the API Key when sharing the source code?

Example: I want to share a similar project on github so someone can collaborate with me. But I don't want the API Key to become visible to everyone.

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

Open or create C:\Users\USERNAME.gradle\gradle.properties

Add the line: ForcasteIOAPIKey=YOUR_API_KEY

Replace YOUR_API_KEY above with your api key.

Then, in your module's build.gradle file, add the following:

def FORCASTE_IO_API_KEY = '"' + ForcasteIOAPIKey+ '"' ?: '"Missing Forcaste IO API Key"';

and add to the all section in buildTypes:

buildTypes {
    all {
        buildConfigField 'String', 'FORCASTE_IO_API_KEY ', FORCASTE_IO_API_KEY
    }
    (...)
}

Finally, To access the API key in your code use BuildConfig.FORCASTE_IO_API_KEY