Andres Mora
Andres Mora

Reputation: 1117

How to send accented characters with diacritics in HTTP request-payload?

I am requiring to send special characters like accented characters with diacritics, e.g. o-acute ó, via API

This is my test code

import string
import http.client
import datetime
import json

def apiSendFarmacia(idatencion,articulo,deviceid):
    ##API PAYLOAD
    now = datetime.datetime.now()
    conn = http.client.HTTPSConnection("apimocha.com")
    payload = json.dumps({
      "idatencion": idatencion,
      "articulo": articulo,
      "timestamp": str(now),
      "deviceId": deviceid
      
    }).encode("utf-8")
    headers = {
      'Content-Type': 'application/json'
    }
    conn.request("POST"
                ,"/xxxx/api2"#"/my/api/path" #"/alexa"
                , payload
                , headers)
    res = conn.getresponse()
    httpcode = res.status
    data = res.read()
    return httpcode#, data.decode("utf-8")
    ##API PAYLOAD

when executing the function with some special characters

apiSendFarmacia(2222,"solución",2222)

the mock API will receive following JSON payload with \u00f3 instead of ó:

{
      "idatencion": 2222,
      "articulo": "soluci\u00f3n",
      "timestamp": "2022-12-07 14:52:24.878976",
      "deviceId": 2222
}

I was expecting the special character with its accent-mark ó to show in the mock API.

Upvotes: 0

Views: 771

Answers (1)

nokla
nokla

Reputation: 1590

As you print it, it will appear as the special character:

>>> print('soluci\u00f3n')
solución

u00f3 denotes the hexadecimal representation for Unicode Character 'LATIN SMALL LETTER O WITH ACUTE' (U+00F3).

The \ is an escape-signal that tells the interpreter that the subsequent character(s) has to be treated as special character. For example \n is interpreted as newline, \t as tab and \u00f3 as Unicode character ó.

Upvotes: 4

Related Questions