API Key Error 401 unauthorized

I’m getting the following error :
“error”: {
“message”: “You didn’t provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you’re accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.”,
“type”: “invalid_request_error”,
“param”: null,
“code”: null

this is theChatRepository class that interacts with OpenAI API using Retrofit:

class ChatRepository {

private val apiClient = ApiClient.retrofitService

fun createChatCompletion(message : String){

   /* CoroutineScope(Dispatchers.IO)
        .launch {*/
                val chatRequest = ChatRequest(arrayListOf(
                    Message("Introduce your self and Lets ask me what topic I want to discuss"

                apiClient.createChatCompletion(chatRequest).enqueue(object : Callback<ChatResponse>{
                        override fun onResponse(
                            call: Call<ChatResponse>,
                            response: Response<ChatResponse>
                        ) {
                            val code = response.code()
                            println("chat request : $chatRequest")
                            println("chat resp : $response")
                                val msg = response.body()?.choices?.get(0)?.message
                                if (msg != null)
                                {println("message $msg" )}
                                else {
                                    println("msg null")
                                val message = response.body()?.choices?.get(0)?.message

                                Log.d("message", message?.toString() ?: "Message is null")

                            else {

                        override fun onFailure(call: Call<ChatResponse>, t: Throwable) {


            catch (e: Exception){


this is ApiClient object that configures a Retrofit instance for making API requests :
object ApiClient {

private val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
    // we need to add converter factory to
    // convert JSON object to Java object
 * A public Api object that exposes the lazy-initialized Retrofit service
val retrofitService : ApiInterface by lazy { retrofit.create(ApiInterface::class.java) }

/*fun getInstance (): ApiInterface{
        return retrofitService

this is the ApiInterface that defines a Retrofit interface for making API requests. It sends a POST request to OpenAI GPT-3 chat completion API :

interface ApiInterface {

@POST("chat/completions?Content-Type=application/json&Authorization=Bearer $OPENAI_API_KEY")
fun createChatCompletion(
    @Body chatRequest : ChatRequest,

    ) : Call<ChatResponse>

Please I need your help , I’ve been stuck on this error for too long :sob: :sob:

1 Like

What is the source of this code? Where is the model defined?

The API key is certainly not transmitted as a query string as part of the URL. It is part of the headers of a request. It must not be made available to man-in-the-middle attacks by being in a URL.

But most importantly, it appears that you are trying to write client code that would access the OpenAI API directly, and then you’d have to place the API key within that code…where anybody can steal it and abuse it.

The OpenAI API key is your access to your account where you have loaded prepaid credits to make use of the OpenAI services, and the key must be kept secret, and be kept off of consumer devices.

1 Like

I hate to be that guy, but did you read the error message?

  • You need to supply an API key.
  • You didn’t supply an API key.
  • If you don’t have an API key you can get one at, https://platform.openai.com/account/api-keys.
  • Go there, get an API key, and give it to this code that you don’t understand and hope nothing bad happens.