{"id":19635717,"url":"https://github.com/codepath/android-rest-client-template-kotlin","last_synced_at":"2025-10-09T06:53:47.352Z","repository":{"id":67987427,"uuid":"357004838","full_name":"codepath/android-rest-client-template-kotlin","owner":"codepath","description":"Template Creating an Android OAuth REST Client (Kotlin)","archived":false,"fork":false,"pushed_at":"2022-01-06T03:57:27.000Z","size":163,"stargazers_count":3,"open_issues_count":0,"forks_count":1,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-02-26T21:45:04.923Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codepath.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-04-11T23:42:23.000Z","updated_at":"2023-03-16T16:24:34.000Z","dependencies_parsed_at":null,"dependency_job_id":"a83d2d8c-8f32-4386-b8f7-b69f374f0a20","html_url":"https://github.com/codepath/android-rest-client-template-kotlin","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/codepath/android-rest-client-template-kotlin","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fandroid-rest-client-template-kotlin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fandroid-rest-client-template-kotlin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fandroid-rest-client-template-kotlin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fandroid-rest-client-template-kotlin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codepath","download_url":"https://codeload.github.com/codepath/android-rest-client-template-kotlin/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fandroid-rest-client-template-kotlin/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279000861,"owners_count":26082951,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-09T02:00:07.460Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-11T12:26:38.791Z","updated_at":"2025-10-09T06:53:47.338Z","avatar_url":"https://github.com/codepath.png","language":"Kotlin","funding_links":[],"categories":[],"sub_categories":[],"readme":"# RestClientTemplate\n\n## Overview\n\nRestClientTemplate is a skeleton Android project that makes writing Android apps sourced from OAuth JSON REST APIs as easy as possible. This skeleton project\ncombines the best libraries and structure to enable quick development of rich API clients. The following things are supported out of the box:\n\n * Authenticating with any OAuth 1.0a or OAuth 2 API\n * Sending requests for and parsing JSON API data using a defined client\n * Persisting data to a local SQLite store through an ORM layer\n * Displaying and caching remote image data into views\n\nThe following libraries are used to make this possible:\n\n * [scribe-java](https://github.com/fernandezpablo85/scribe-java) - Simple OAuth library for handling the authentication flow.\n * [Android Async HTTP](https://github.com/codepath/AsyncHttpClient) - Simple asynchronous HTTP requests with JSON parsing\n * [codepath-oauth](https://github.com/thecodepath/android-oauth-handler) - Custom-built library for managing OAuth authentication and signing of requests\n * [Glide](https://github.com/bumptech/glide) - Used for async image loading and caching them in memory and on disk.\n * [Room](https://developer.android.com/training/data-storage/room/index.html) - Simple ORM for persisting a local SQLite database on the Android device\n\n## Usage\n\n### 1. Configure the REST client\n\nOpen `src/com.codepath.apps.restclienttemplate/RestClient.java`. Configure the `REST_API_INSTANCE` and`REST_URL`.\n\nFor example if I wanted to connect to Twitter:\n\n```kotlin\n// RestClient.kt\nclass RestClient(context: Context) : OAuthBaseClient {\n    companion object {\n        val REST_API_INSTANCE = TwitterApi.instance()\n\n        const val REST_URL = \"https://api.twitter.com/1.1\"\n\n        const val REST_CONSUMER_KEY =\n            BuildConfig.CONSUMER_KEY // Change this inside apikey.properties\n\n        const val REST_CONSUMER_SECRET =\n            BuildConfig.CONSUMER_SECRET // Change this inside apikey.properties\n\n        // ...constructor and endpoints\n    }\n\n}\n```\n\nRename the `apikey.properties.example` file to `apikey.properties`.   Replace the `CONSUMER_KEY` and `CONSUMER_SECRET` to the values specified in the Twitter console:\n\nCONSUMER_KEY=\"adsflfajsdlfdsajlafdsjl\"\nCONSUMER_SECRET=\"afdsljkasdflkjsd\"\n\nNext, change the `intent_scheme` and `intent_host` in `strings.xml` to a unique name that is special for this application.\nThis is used for the OAuth authentication flow for launching the app through web pages through an [Android intent](https://developer.chrome.com/multidevice/android/intents).\n\n```xml\n\u003cstring name=\"intent_scheme\"\u003eoauth\u003c/string\u003e\n\u003cstring name=\"intent_host\"\u003ecodepathtweets\u003c/string\u003e\n```\n\nNext, you want to define the endpoints which you want to retrieve data from or send data to within your client:\n\n```kotlin\n// RestClient.jt\nfun getHomeTimeline(page: Int, handler: JsonHttpResponseHandler) {\n  val apiUrl = getApiUrl(\"statuses/home_timeline.json\")\n  val params = RequestParams()\n  params.put(\"page\", String.valueOf(page))\n  client.get(apiUrl, params, handler)\n}\n```\n\nNote we are using `getApiUrl` to get the full URL from the relative fragment and `RequestParams` to control the request parameters.\nYou can easily send post requests (or put or delete) using a similar approach:\n\n```kotlin\n// RestClient.kt\nfun postTweet(body: String, handler: JsonHttpResponseHandler) {\n    val apiUrl = getApiUrl(\"statuses/update.json\")\n    val params = RequestParams()\n    params.put(\"status\", body)\n    client.post(apiUrl, params, handler)\n}\n```\n\nThese endpoint methods will automatically execute asynchronous requests signed with the authenticated access token. To use JSON endpoints, simply invoke the method\nwith a `JsonHttpResponseHandler` handler:\n\n```kotlin\n// SomeActivity.kt\nval client = RestApplication.getRestClient()\nclient.getHomeTimeline(object : JsonHttpResponseHandler() {\n    override fun onSuccess(statusCode: Int, headers: okhttp3.Headers, json: JSON) {\n        Log.i(TAG, \"onSuccess!\")\n        // parse json response here\n    }\n\n    override fun onFailure(\n        statusCode: Int,\n        headers: okhttp3.Headers,\n        response: String,\n        throwable: Throwable\n    ) {\n        Log.i(TAG, \"onFailure!\", throwable)\n    }\n\n})\n```\n\nBased on the JSON response (array or object), you need to declare the expected type inside the OnSuccess signature i.e\n`public void onSuccess(JSONObject json)`. If the endpoint does not return JSON, then you can use the `AsyncHttpResponseHandler`:\n\n```kotlin\nval client = RestApplication.getRestClient()\nclient.getSomething(object : JsonHttpResponseHandler() {\n    override fun onSuccess (statusCode: Int, headers: Headers, json: JSON) {\n        System.out.println(json)\n    }\n});\n```\nCheck out [Android Async HTTP Docs](https://github.com/codepath/AsyncHttpClient) for more request creation details.\n\n### 2. Define the Models\n\nIn the `src/com.codepath.apps.restclienttemplate.models`, create the models that represent the key data to be parsed and persisted within your application.\n\nFor example, if you were connecting to Twitter, you would want a Tweet model as follows:\n\n```kotlin\n// models/Tweet.kt\npackage com.codepath.apps.restclienttemplate.models\n\nimport androidx.room.ColumnInfo\nimport androidx.room.Embedded\n\nimport androidx.room.Entity\nimport androidx.room.PrimaryKey\n\nimport org.json.JSONException\nimport org.json.JSONObject\n\n@Entity\nclass Tweet {\n  // Define database columns and associated fields\n  @PrimaryKey\n  @ColumnInfo\n  var id: Long = 0L\n\n  @ColumnInfo\n  var userHandle: String = \"\"\n\n  @ColumnInfo\n  var timestamp: String = \"\"\n\n  @ColumnInfo\n  var body: String = \"\"\n\n  // Use @Embedded to keep the column entries as part of the same table while still\n  // keeping the logical separation between the two objects.\n  @Embedded\n  @Nullable\n  var user: User = null\n}\n```\n\nNote there is a separate `User` object but it will not actually be declared as a separate table.  By using the `@Embedded` annotation, the fields in this class will be stored as part of the Tweet table.  Room specifically does not load references between two different entities for performance reasons (see https://developer.android.com/training/data-storage/room/referencing-data), so declaring it this way causes the data to be denormalized as one table.\n\n```kotlin\n// models/User.java\n\nclass User {\n\n    @ColumnInfo\n    var name: String + \"\"\n\n    // normally this field would be annotated @PrimaryKey because this is an embedded object\n    // it is not needed\n    @ColumnInfo\n    var twitter_id: Long = 0L\n}\n```\nNotice here we specify the SQLite table for a resource, the columns for that table, and a constructor for turning the JSON object fetched from the API into this object. For more information on creating a model, check out the [Room guide](https://developer.android.com/training/data-storage/room/).\n\nIn addition, we also add functions into the model to support parsing JSON attributes in order to instantiate the model based on API data.  For the User object, the parsing logic would be:\n\n```kotlin\n// Parse model from JSON\ncompanion object {\n    fun parseJSON(tweetJson: JSONObject) : User {\n        val user = User()\n        this.twitter_id = tweetJson.getLong(\"id\")\n        this.name = tweetJson.getString(\"name\")\n        return user\n    }\n}\n```\n\nFor the Tweet object, the logic would would be:\n\n```kotlin\n// models/Tweet.kt\n@Entity\ncompanion object {\n    fun fromJson(jsonObject: JSONObject): Tweet {\n        val tweet = Tweet()\n        tweet.body = jsonObject.getString(\"text\")\n        tweet.createdAt = jsonObject.getString(\"created_at\")\n        tweet.user = User.fromJson(jsonObject.getJSONObject(\"user\"))\n        return tweet\n    }\n\n    fun fromJsonArray(jsonArray: JSONArray): List\u003cTweet\u003e {\n        val tweets = ArrayList\u003cTweet\u003e()\n        for (i in 0 until jsonArray.length()) {\n            tweets.add(fromJson(jsonArray.getJSONObject(i)))\n        }\n        return tweets\n    }\n}\n```\n\n\nNow you have a model that supports proper creation based on JSON. Create models for all the resources necessary for your mobile client.\n\n### 4. Define your queries\n\nNext, you will need to define the queries by creating a Data Access Object (DAO) class.   Here is an example of declaring queries to return a Tweet by the post ID, retrieve the most recent tweets, and insert tweets.\n\n```kotlin\n\nimport androidx.room.Dao\nimport androidx.room.Insert\nimport androidx.room.OnConflictStrategy\nimport androidx.room.Query\n\nimport java.util.List\n\n@Dao\ninterface TwitterDao {\n    // @Query annotation requires knowing SQL syntax\n    // See http://www.sqltutorial.org/\n    @Query(\"SELECT * FROM SampleModel WHERE id = :id\")\n    fun byTweetId(tweetId: Long): Tweet?\n\n    @Query(\"SELECT * FROM Tweet ORDER BY created_at\")\n    fun getRecentTweets(): List\u003cTweet\u003e\n\n    // Replace strategy is needed to ensure an update on the table row.  Otherwise the insertion will\n    // fail.\n    @Insert(onConflict = OnConflictStrategy.REPLACE)\n    fun insertTweet(tweets: List\u003cTweet\u003e);\n}\n```\n\nThe examples here show how to perform basic queries on the Tweet table.  If you need to declare one-to-many or many-to-many relations, see the guides on using the [@Relation](https://developer.android.com/reference/android/arch/persistence/room/Relation) and [@ForeignKey](https://developer.android.com/reference/android/arch/persistence/room/ForeignKey) annotations.\n\n### 5. Create database\n\nWe need to define a database that extends `RoomDatabase` and describe which entities as part of this database. We also need to include what data access objects are to be included.  If the entities are modified or additional ones are included, the version number will need to be changed.  Note that only the `Tweet` class is declared:\n\n```kotlin\n// bump version number if your schema changes\n@Database(entities={Tweet.class}, version=1)\nabstract class MyDatabase : RoomDatabase() {\n    abstract fun sampleModelDao(): SampleModelDao?\n\n    companion object {\n        // Database name to be used\n        const val NAME = \"MyDataBase\"\n    }\n}\n```\n\nWhen compiling the code, the schemas will be stored in a `schemas/` directory assuming this statement\nhas been included your `app/build.gradle` file.  These schemas should be checked into your code based.\n\n```gradle\nandroid {\n    defaultConfig {\n\n        javaCompileOptions {\n            annotationProcessorOptions {\n                arguments = [\"room.schemaLocation\": \"$projectDir/schemas\".toString()]\n            }\n        }\n    }\n\n}\n```\n\n### 6. Initialize database\n\nInside your application class, you will need to initialize the database and specify a name for it.\n\n```kotlin\nclass RestClientApp : Application {\n\n  var myDatabase: MyDatabase = null\n\n  override fun onCreate() {\n    // when upgrading versions, kill the original tables by using fallbackToDestructiveMigration()\n    myDatabase = Room.databaseBuilder(this, MyDatabase.class, MyDatabase.NAME).fallbackToDestructiveMigration().build()\n  }\n\n  fun getMyDatabase(): MyDatabase {\n    return myDatabase\n  }\n\n}\n```\n\n### 7. Setup Your Authenticated Activities\n\nOpen `src/com.codepath.apps.restclienttemplate/LoginActivity.kt` and configure the `onLoginSuccess` method\nwhich fires once your app has access to the authenticated API. Launch an activity and begin using your REST client:\n\n```kotlin\n// LoginActivity.kt\noverride fun onLoginSuccess() {\n  val intent = Intent(this, TimelineActivity:class.java)\n  startActivity(i);\n}\n```\n\nIn your new authenticated activity, you can access your client anywhere with:\n\n```kotlin\nval client = RestApplication.getRestClient()\nclient.getHomeTimeline(object : JsonHttpResponseHandler() {\n  fun onSuccess(statusCode: Int, headers: Headers , json: JSON) {\n    Log.d(\"DEBUG\", \"timeline: \" + json.jsonArray.toString())\n    // Load json array into model classes\n  }\n});\n```\n\nYou can then load the data into your models from a `JSONArray` using:\n\n```kotlin\nval tweets = Tweet.fromJSON(jsonArray)\n```\n\nor load the data from a single `JSONObject` with:\n\n```kotlin\nval tweet = Tweet(json)\n// t.body = \"foo\"\n```\n\nTo save, you will need to perform the database operation on a separate thread by creating an `AsyncTask` and adding the item:\n\n```kotlin\nval task = object: AsyncTask\u003cTweet, Void, Void\u003e() {\n    override fun doInBackground(List\u003cTweet\u003e tweets) {\n      val twitterDao = (getApplicationContext() as RestApplication).getMyDatabase().twitterDao()\n      twitterDao.insertModel(tweets)\n      return null;\n    };\n  };\n  task.execute(tweets);\n```\n\nThat's all you need to get started. From here, hook up your activities and their behavior, adjust your models and add more REST endpoints.\n\n### Extras\n\n#### Loading Images with Glide\n\nIf you want to load a remote image url into a particular ImageView, you can use Glide to do that with:\n\n```kotlin\nGlide.with(this).load(imageUrl)\n     .into(imageView);\n```\n\nThis will load an image into the specified ImageView and resize the image to fit.\n\n#### Logging Out\n\nYou can log out by clearing the access token at any time through the client object:\n\n```kotlin\nval client = RestApplication.getRestClient()\nclient.clearAccessToken()\n```\n\n### Viewing SQL table\n\nYou can use `chrome://inspect` to view the SQL tables once the app is running on your emulator.  See [this guide](https://guides.codepath.com/android/Debugging-with-Stetho) for more details.\n\n### Adding OAuth2 support\n\nGoogle uses OAuth2 APIs so make sure to use the `GoogleApi20` instance:\n\n```kotlin\ncompanion object {\n  const val REST_API_INSTANCE = GoogleApi20.instance()\n}\n```\n\nChange `REST_URL` to use the Google API:\n\n```java\npublic static final String REST_URL = \"https://www.googleapis.com/calendar/v3\"; // Change this, base API URL\n```\n\nThe consumer and secret keys should be retrieved via [the credentials section](https://console.developers.google.com/apis/credentials) in the Google developer console  You will need to create an OAuth2 client ID and client secret.\n\nCreate a file called `apikey.properties`:\n\n```kotlin\nREST_CONSUMER_KEY=\"XXX-XXX.apps.googleusercontent.com\"\nREST_CONSUMER_SECRET=\"XX-XXXXXXX\"\n```\n\nThe OAuth2 scopes should be used according to the ones defined in [the OAuth2 scopes](https://developers.google.com/identity/protocols/googlescopes):\n\n```kotlin\ncompanion object {\n  const val OAUTH2_SCOPE = \"https://www.googleapis.com/auth/calendar.readonly\"\n}\n```\n\nMake sure to pass this value into the scope parameter:\n\n```kotlin\nconstructor RestClient(context: Context) {\n\t\tthis(context, REST_API_INSTANCE,\n\t\t\t\tREST_URL,\n\t\t\t\tREST_CONSUMER_KEY,\n\t\t\t\tREST_CONSUMER_SECRET,\n\t\t\t\tOAUTH2_SCOPE,  // OAuth2 scope, null for OAuth1\n\t\t\t\tString.format(REST_CALLBACK_URL_TEMPLATE, context.getString(R.string.intent_host),\n\t\t\t\t\t\tcontext.getString(R.string.intent_scheme), context.getPackageName(), FALLBACK_URL));\n\t}\n```\nGoogle only accepts `http://` or `https://` domains, so your `REST_CALLBACK_URL_TEMPLATE` will need to be adjusted:\n\n```kotlin\ncompanion object {\n  const val REST_CALLBACK_URL_TEMPLATE = \"https://localhost\"\n}\n```\n\nMake sure to update the `cprest` and `intent_host` to match this callback URL .\n\n### Troubleshooting\n\n* If you receive the following error `org.scribe.exceptions.OAuthException: Cannot send unauthenticated requests for TwitterApi client. Please attach an access token!` then check the following:\n * Is your intent-filter with `\u003cdata\u003e` attached to the `LoginActivity`? If not, make sure that the `LoginActivity` receives the request after OAuth authorization.\n * Is the `onLoginSuccess` method being executed in the `LoginActivity`. On launch of your app, be sure to start the app on the LoginActivity so authentication routines execute on launch and take you to the authenticated activity.\n * If you are plan to test with Android API 24 or above, you will need to use Chrome to launch the OAuth flow.\n * Note that the emulators (both the Google-provided x86 and Genymotion versions) for API 24+ versions can introduce intermittent issues when initiating the OAuth flow for the first time.  For best results, use an device for this project.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodepath%2Fandroid-rest-client-template-kotlin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodepath%2Fandroid-rest-client-template-kotlin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodepath%2Fandroid-rest-client-template-kotlin/lists"}