{"activeVersionTag":"latest","latestAvailableVersionTag":"latest","collection":{"info":{"_postman_id":"8fcbd36a-1ac7-4800-8eb8-59cda5c86b5e","name":"Retrofit Web Server (Kotlin & Node.js)","description":"This documentation provides details for the RESTful API created using Node.js and Express. The API includes endpoints for creating, reading, updating, and deleting items.\n\nCreating a web server with node and express. The in client side of android with Kotlin used retrofit for HTTP connection with server.\n\nGithub Repository : [https://github.com/abtaaahi/Retrofit-Web-Server-Kotlin-Node.js](https://github.com/abtaaahi/Retrofit-Web-Server-Kotlin-Node.js)\n\n### Base URL\n\n`http://localhost:1113`\n\n``` kotlin\ndependencies {\n    implementation(\"com.squareup.retrofit2:retrofit:2.9.0\")\n    implementation(\"com.squareup.retrofit2:converter-gson:2.9.0\")\n    implementation(\"com.squareup.okhttp3:logging-interceptor:4.9.0\")\n}\n\n ```\n\nCreate a `ApiService` for RESTful API:\n\n``` kotlin\nimport retrofit2.Call\nimport retrofit2.http.*\ninterface ApiService {\n    @GET(\"get\")\n    fun getItems(): Call<List<Item>>\n    @GET(\"get/{id}\")\n    fun getItem(@Path(\"id\") id: Int): Call<Item>\n    @POST(\"post\")\n    fun createItem(@Body item: Item): Call<Item>\n    @PUT(\"update/{id}\")\n    fun updateItem(@Path(\"id\") id: Int, @Body item: Item): Call<Item>\n    @DELETE(\"delete/{id}\")\n    fun deleteItem(@Path(\"id\") id: Int): Call<Void>\n}\n\n ```\n\nCreate a data class `Item` :\n\n``` kotlin\ndata class Item (\n    val id: Int = 0,\n    val name: String,\n    val course: String\n)\n\n ```\n\nInitialize Retrofit in a singleton\n\n``` kotlin\nimport retrofit2.Retrofit\nimport retrofit2.converter.gson.GsonConverterFactory\nimport okhttp3.OkHttpClient\nimport okhttp3.logging.HttpLoggingInterceptor\nobject RetrofitInstance {\n    private const val BASE_URL = \"http://192.168.1.13:1113/\"\n    private val loggingInterceptor = HttpLoggingInterceptor().apply {\n        setLevel(HttpLoggingInterceptor.Level.BODY)\n    }\n    private val client = OkHttpClient.Builder()\n        .addInterceptor(loggingInterceptor)\n        .build()\n    val retrofit: Retrofit by lazy {\n        Retrofit.Builder()\n            .baseUrl(BASE_URL)\n            .client(client)\n            .addConverterFactory(GsonConverterFactory.create())\n            .build()\n    }\n    val apiService: ApiService by lazy {\n        retrofit.create(ApiService::class.java)\n    }\n}\n\n ```\n\n`MainActivity.kt`\n\n``` kotlin\nimport android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport retrofit2.Call\nimport retrofit2.Callback\nimport retrofit2.Response\nimport android.widget.Button\nimport android.widget.EditText\nimport android.widget.TextView\nclass MainActivity : AppCompatActivity() {\n    private val apiService = RetrofitInstance.apiService\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main)\n        btnGet.setOnClickListener { getItem() }\n        btnPost.setOnClickListener { createItem() }\n        btnPut.setOnClickListener { updateItem() }\n        btnDelete.setOnClickListener { deleteItem() }\n    }\n    private fun getItem() {\n        val idText = etId.text.toString()\n        if (idText.isEmpty()) {\n            apiService.getItems().enqueue(object : Callback<List<Item>> {\n                override fun onResponse(call: Call<List<Item>>, response: Response<List<Item>>) {\n                    if (response.isSuccessful) {\n                        val items = response.body() ?: emptyList()\n                        tvResult.text = if (items.isNotEmpty()) {\n                            \"${items.joinToString(separator = \"\\n\") { \"${it.id}: ${it.name}, ${it.course}\" }}\"\n                        } else {\n                            \"No items found.\"\n                        }\n                    } else {\n                        tvResult.text = \"GET ALL Error: ${response.code()}\"\n                    }\n                }\n                override fun onFailure(call: Call<List<Item>>, t: Throwable) {\n                    tvResult.text = \"GET ALL Failure: ${t.message}\"\n                }\n            })\n        } else {\n            val id = idText.toIntOrNull()\n            if (id != null) {\n                apiService.getItem(id).enqueue(object : Callback<Item> {\n                    override fun onResponse(call: Call<Item>, response: Response<Item>) {\n                        if (response.isSuccessful) {\n                            tvResult.text = \"${response.body()?.let { \"${it.id}: ${it.name}, ${it.course}\" }}\"\n                        } else {\n                            tvResult.text = \"GET Error: ${response.code()}\"\n                        }\n                    }\n                    override fun onFailure(call: Call<Item>, t: Throwable) {\n                        tvResult.text = \"GET Failure: ${t.message}\"\n                    }\n                })\n            } else {\n                tvResult.text = \"Invalid ID. Please enter a valid numeric ID.\"\n            }\n        }\n    }\n    private fun createItem() {\n        val id = etId.text.toString().toIntOrNull() ?: 0\n        val name = etName.text.toString()\n        val course = etDescription.text.toString()\n        val newItem = Item(id = id, name = name, course = course)\n        apiService.createItem(newItem).enqueue(object : Callback<Item> {\n            override fun onResponse(call: Call<Item>, response: Response<Item>) {\n                if (response.isSuccessful) {\n                    tvResult.text = \"POST Success: ${response.body()}\"\n                } else {\n                    tvResult.text = \"POST Error: ${response.code()}\"\n                }\n            }\n            override fun onFailure(call: Call<Item>, t: Throwable) {\n                tvResult.text = \"POST Failure: ${t.message}\"\n            }\n        })\n    }\n    private fun updateItem() {\n        val id = etId.text.toString().toIntOrNull()\n        if (id != null) {\n            val name = etName.text.toString()\n            val course = etDescription.text.toString()\n            val updatedItem = Item(id = id, name = name, course = course)\n            apiService.updateItem(id, updatedItem).enqueue(object : Callback<Item> {\n                override fun onResponse(call: Call<Item>, response: Response<Item>) {\n                    if (response.isSuccessful) {\n                        tvResult.text = \"PUT Success: ${response.body()}\"\n                    } else {\n                        tvResult.text = \"PUT Error: ${response.code()}\"\n                    }\n                }\n                override fun onFailure(call: Call<Item>, t: Throwable) {\n                    tvResult.text = \"PUT Failure: ${t.message}\"\n                }\n            })\n        } else {\n            tvResult.text = \"Please enter a valid ID\"\n        }\n    }\n    private fun deleteItem() {\n        val id = etId.text.toString().toIntOrNull()\n        if (id != null) {\n            apiService.deleteItem(id).enqueue(object : Callback<Void> {\n                override fun onResponse(call: Call<Void>, response: Response<Void>) {\n                    if (response.isSuccessful) {\n                        tvResult.text = \"DELETE Success: ${response.code()}\"\n                    } else {\n                        tvResult.text = \"DELETE Error: ${response.code()}\"\n                    }\n                }\n                override fun onFailure(call: Call<Void>, t: Throwable) {\n                    tvResult.text = \"DELETE Failure: ${t.message}\"\n                }\n            })\n        } else {\n            tvResult.text = \"Please enter a valid ID\"\n        }\n    }\n}\n\n ```\n\n`network-security-config.xml` in res/xml:\n\n``` xml\n<network-security-config>\n<base-config cleartextTrafficPermitted=\"true\">\n    <trust-anchors>\n        <certificates src=\"system\" />\n    </trust-anchors>\n</base-config>\n</network-security-config>\n\n ```\n\n`AndroidManifest.xml`\n\n``` xml\n<manifest>\n    <uses-permission android:name=\"android.permission.INTERNET\"></uses-permission>\n            android:networkSecurityConfig=\"@xml/network_security_config\"\n        android:usesCleartextTraffic=\"true\"\n    </application>\n</manifest>\n\n ```\n\nServer Setup:\n\n`mkdir node-web-server`\n\n`cd node-web-server`\n\n`npm init -y`\n\n`npm install express`\n\n`Server.js :`\n\n``` javascript\nconst express = require('express')\nconst app = express()\nconst port = 1113\napp.use(express.json())\nlet data = [\n    { id: 1, name: 'Alex', course: 'Computer Science'},\n    { id: 2, name: 'John', course: 'Electrical'},\n    { id: 3, name: 'Charlie', course: 'Civil'},\n    { id: 4, name: 'JohnWick', course: 'Mathematics' },\n    { id: 5, name: 'Jane', course: 'Physics' },\n    { id: 6, name: 'Smith', course: 'Chemistry' }\n]\n//Read all items\napp.get('/get', (req, res) => {\n    res.json(data)\n})\n//Read specific item\napp.get('/get/:id', (req, res) => {\n    const id = parseInt(req.params.id)\n    const item = data.find( i => i.id === id)\n    if(item){\n        res.json(item)\n    } else{\n        res.status(404).send('Item Not Fund')\n    }\n})\n//Create a new item\napp.post('/post', (req, res) => {\n    const newItem =  { id: data.length + 1, ...req.body}\n    data.push(newItem)\n    res.status(201).json(newItem)\n})\n//Update an item\napp.put('/update/:id', (req, res) => {\n    const id = parseInt(req.params.id);\n    const index = data.findIndex(i => i.id === id);\n    if (index !== -1) {\n      data[index] = { id, ...req.body };\n      res.json(data[index]);\n    } else {\n      res.status(404).send('Item not found');\n    }\n});\n// Delete an item\napp.delete('/delete/:id', (req, res) => {\n    const id = parseInt(req.params.id);\n    const index = data.findIndex(i => i.id === id);\n    if (index !== -1) {\n      const deletedItem = data.splice(index, 1);\n      res.json(deletedItem[0]);\n      res.send(`Item deleted`);\n    } else {\n      res.status(404).send('Item not found');\n    }\n});\napp.get('/', (req, res) => {\n  res.send(`Server running successfully`);\n});\napp.listen(port, () => {\n    console.log(`Server running at http://localhost:${port}/`)\n})\n\n ```\n\n`package.json:`\n\n``` json\n{\n  \"name\": \"web-server\",\n  \"version\": \"1.0.0\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"description\": \"\",\n  \"dependencies\": {\n    \"express\": \"^4.19.2\"\n  }\n}\n\n ```\n\n`node server.js`","schema":"https://schema.getpostman.com/json/collection/v2.0.0/collection.json","isPublicCollection":false,"owner":"36920253","collectionId":"8fcbd36a-1ac7-4800-8eb8-59cda5c86b5e","publishedId":"2sA3s3GWia","public":true,"publicUrl":"https://documenter-api.postman.tech/view/36920253/2sA3s3GWia","privateUrl":"https://go.postman.co/documentation/36920253-8fcbd36a-1ac7-4800-8eb8-59cda5c86b5e","customColor":{"top-bar":"FFFFFF","right-sidebar":"303030","highlight":"FF6C37"},"documentationLayout":"classic-double-column","customisation":{"metaTags":[{"name":"description","value":"This documentation provides details for the RESTful API created using Node.js and Express. The API includes endpoints for creating, reading, updating, and deleting items.\n\nCreating a web server with node and express. The in client side of android with Kotlin used retrofit for HTTP connection with server."},{"name":"title","value":""}],"appearance":{"default":"system_default","themes":[{"name":"dark","logo":null,"colors":{"top-bar":"212121","right-sidebar":"303030","highlight":"FF6C37"}},{"name":"light","logo":null,"colors":{"top-bar":"FFFFFF","right-sidebar":"303030","highlight":"FF6C37"}}]}},"version":"8.10.0","publishDate":"2024-08-09T20:13:26.000Z","activeVersionTag":"latest","documentationTheme":"light","metaTags":{"title":"","description":"This documentation provides details for the RESTful API created using Node.js and Express. The API includes endpoints for creating, reading, updating, and deleting items.\n\nCreating a web server with node and express. The in client side of android with Kotlin used retrofit for HTTP connection with server."},"logos":{"logoLight":null,"logoDark":null}},"statusCode":200},"environments":[],"user":{"authenticated":false,"permissions":{"publish":false}},"run":{"button":{"js":"https://run.pstmn.io/button.js","css":"https://run.pstmn.io/button.css"}},"web":"https://www.getpostman.com/","team":{"logo":"https://res.cloudinary.com/postman/image/upload/t_team_logo_pubdoc/v1/team/768118b36f06c94b0306958b980558e6915839447e859fe16906e29d683976f0","favicon":""},"isEnvFetchError":false,"languages":"[{\"key\":\"csharp\",\"label\":\"C#\",\"variant\":\"HttpClient\"},{\"key\":\"csharp\",\"label\":\"C#\",\"variant\":\"RestSharp\"},{\"key\":\"curl\",\"label\":\"cURL\",\"variant\":\"cURL\"},{\"key\":\"dart\",\"label\":\"Dart\",\"variant\":\"http\"},{\"key\":\"go\",\"label\":\"Go\",\"variant\":\"Native\"},{\"key\":\"http\",\"label\":\"HTTP\",\"variant\":\"HTTP\"},{\"key\":\"java\",\"label\":\"Java\",\"variant\":\"OkHttp\"},{\"key\":\"java\",\"label\":\"Java\",\"variant\":\"Unirest\"},{\"key\":\"javascript\",\"label\":\"JavaScript\",\"variant\":\"Fetch\"},{\"key\":\"javascript\",\"label\":\"JavaScript\",\"variant\":\"jQuery\"},{\"key\":\"javascript\",\"label\":\"JavaScript\",\"variant\":\"XHR\"},{\"key\":\"c\",\"label\":\"C\",\"variant\":\"libcurl\"},{\"key\":\"nodejs\",\"label\":\"NodeJs\",\"variant\":\"Axios\"},{\"key\":\"nodejs\",\"label\":\"NodeJs\",\"variant\":\"Native\"},{\"key\":\"nodejs\",\"label\":\"NodeJs\",\"variant\":\"Request\"},{\"key\":\"nodejs\",\"label\":\"NodeJs\",\"variant\":\"Unirest\"},{\"key\":\"objective-c\",\"label\":\"Objective-C\",\"variant\":\"NSURLSession\"},{\"key\":\"ocaml\",\"label\":\"OCaml\",\"variant\":\"Cohttp\"},{\"key\":\"php\",\"label\":\"PHP\",\"variant\":\"cURL\"},{\"key\":\"php\",\"label\":\"PHP\",\"variant\":\"Guzzle\"},{\"key\":\"php\",\"label\":\"PHP\",\"variant\":\"HTTP_Request2\"},{\"key\":\"php\",\"label\":\"PHP\",\"variant\":\"pecl_http\"},{\"key\":\"powershell\",\"label\":\"PowerShell\",\"variant\":\"RestMethod\"},{\"key\":\"python\",\"label\":\"Python\",\"variant\":\"http.client\"},{\"key\":\"python\",\"label\":\"Python\",\"variant\":\"Requests\"},{\"key\":\"r\",\"label\":\"R\",\"variant\":\"httr\"},{\"key\":\"r\",\"label\":\"R\",\"variant\":\"RCurl\"},{\"key\":\"ruby\",\"label\":\"Ruby\",\"variant\":\"Net::HTTP\"},{\"key\":\"shell\",\"label\":\"Shell\",\"variant\":\"Httpie\"},{\"key\":\"shell\",\"label\":\"Shell\",\"variant\":\"wget\"},{\"key\":\"swift\",\"label\":\"Swift\",\"variant\":\"URLSession\"}]","languageSettings":[{"key":"csharp","label":"C#","variant":"HttpClient"},{"key":"csharp","label":"C#","variant":"RestSharp"},{"key":"curl","label":"cURL","variant":"cURL"},{"key":"dart","label":"Dart","variant":"http"},{"key":"go","label":"Go","variant":"Native"},{"key":"http","label":"HTTP","variant":"HTTP"},{"key":"java","label":"Java","variant":"OkHttp"},{"key":"java","label":"Java","variant":"Unirest"},{"key":"javascript","label":"JavaScript","variant":"Fetch"},{"key":"javascript","label":"JavaScript","variant":"jQuery"},{"key":"javascript","label":"JavaScript","variant":"XHR"},{"key":"c","label":"C","variant":"libcurl"},{"key":"nodejs","label":"NodeJs","variant":"Axios"},{"key":"nodejs","label":"NodeJs","variant":"Native"},{"key":"nodejs","label":"NodeJs","variant":"Request"},{"key":"nodejs","label":"NodeJs","variant":"Unirest"},{"key":"objective-c","label":"Objective-C","variant":"NSURLSession"},{"key":"ocaml","label":"OCaml","variant":"Cohttp"},{"key":"php","label":"PHP","variant":"cURL"},{"key":"php","label":"PHP","variant":"Guzzle"},{"key":"php","label":"PHP","variant":"HTTP_Request2"},{"key":"php","label":"PHP","variant":"pecl_http"},{"key":"powershell","label":"PowerShell","variant":"RestMethod"},{"key":"python","label":"Python","variant":"http.client"},{"key":"python","label":"Python","variant":"Requests"},{"key":"r","label":"R","variant":"httr"},{"key":"r","label":"R","variant":"RCurl"},{"key":"ruby","label":"Ruby","variant":"Net::HTTP"},{"key":"shell","label":"Shell","variant":"Httpie"},{"key":"shell","label":"Shell","variant":"wget"},{"key":"swift","label":"Swift","variant":"URLSession"}],"languageOptions":[{"label":"C# - HttpClient","value":"csharp - HttpClient - C#"},{"label":"C# - RestSharp","value":"csharp - RestSharp - C#"},{"label":"cURL - cURL","value":"curl - cURL - cURL"},{"label":"Dart - http","value":"dart - http - Dart"},{"label":"Go - Native","value":"go - Native - Go"},{"label":"HTTP - HTTP","value":"http - HTTP - HTTP"},{"label":"Java - OkHttp","value":"java - OkHttp - Java"},{"label":"Java - Unirest","value":"java - Unirest - Java"},{"label":"JavaScript - Fetch","value":"javascript - Fetch - JavaScript"},{"label":"JavaScript - jQuery","value":"javascript - jQuery - JavaScript"},{"label":"JavaScript - XHR","value":"javascript - XHR - JavaScript"},{"label":"C - libcurl","value":"c - libcurl - C"},{"label":"NodeJs - Axios","value":"nodejs - Axios - NodeJs"},{"label":"NodeJs - Native","value":"nodejs - Native - NodeJs"},{"label":"NodeJs - Request","value":"nodejs - Request - NodeJs"},{"label":"NodeJs - Unirest","value":"nodejs - Unirest - NodeJs"},{"label":"Objective-C - NSURLSession","value":"objective-c - NSURLSession - Objective-C"},{"label":"OCaml - Cohttp","value":"ocaml - Cohttp - OCaml"},{"label":"PHP - cURL","value":"php - cURL - PHP"},{"label":"PHP - Guzzle","value":"php - Guzzle - PHP"},{"label":"PHP - HTTP_Request2","value":"php - HTTP_Request2 - PHP"},{"label":"PHP - pecl_http","value":"php - pecl_http - PHP"},{"label":"PowerShell - RestMethod","value":"powershell - RestMethod - PowerShell"},{"label":"Python - http.client","value":"python - http.client - Python"},{"label":"Python - Requests","value":"python - Requests - Python"},{"label":"R - httr","value":"r - httr - R"},{"label":"R - RCurl","value":"r - RCurl - R"},{"label":"Ruby - Net::HTTP","value":"ruby - Net::HTTP - Ruby"},{"label":"Shell - Httpie","value":"shell - Httpie - Shell"},{"label":"Shell - wget","value":"shell - wget - Shell"},{"label":"Swift - URLSession","value":"swift - URLSession - Swift"}],"layoutOptions":[{"value":"classic-single-column","label":"Single Column"},{"value":"classic-double-column","label":"Double Column"}],"versionOptions":[],"environmentOptions":[{"value":"0","label":"No Environment"}],"canonicalUrl":"https://documenter.gw.postman.com/view/metadata/2sA3s3GWia"}