Skip to Content

API Testing using Robot Framework

*** Settings ***
Library           RequestsLibrary
Library           Collections
Library           OperatingSystem
Library           String
Library           JSONLibrary
Resource        ​ secrets.resource

*** Variables ***
${API_URL}        <endpoint url>
${Request File}   request.json

*** Test Cases ***
API test
    Get Authorization Token
    Get POST Response

*** Keywords ***
Get Authorization Token
    [Documentation]    This one will get the Bearer Token
    Create Session    auth    ${TOKEN URL}

    ${payload}=    Create Dictionary
    ...    grant_type=client_credentials
    ...    client_id=${CLIENT_ID}
    ...    client_secret=${CLIENT_SECRET}

    ${headers}=    Create Dictionary
    ...    Content-Type=application/x-www-form-urlencoded

${response}    Post On Session    auth    ${TOKEN_URL}    data=${payload}    headers=${headers}
${Token}       Set Variable       ${response.json()}[access_token]
# Log To Console    ${Token}
${Access_Token}    Catenate    Bearer    ${Token}
RETURN    ${Access_Token}

Create Request Session
    ${Session}        Create Session    PegaRequest    ${API_URL}    verify=true
    ${Response Token} Get Authorization Token
    ${Request Header} Create Dictionary
    Set To Dictionary    ${Request Header}
    ...    Authorization=${Response Token}
    ...    Content-Type=application/json
    ...    User-Agent=PostmanRuntime/7.29.2
    ...    Accept=*/*
    ...    Accept-Encoding=gzip, deflate, br
    ...    Connection=keep-alive
RETURN    ${Session}    ${Request Header}

Get POST Response
    # Pass the json request file here
    ${JSON REQUEST}    Get File    ${Request File}
    Log To Console    ${JSON REQUEST}

    ${json}    Evaluate    json.loads(r'''${JSON REQUEST}''')    json
    Set To Dictionary    ${json['content']['Request']}    CreatedBy=nononon

    # calling the create req function
    ${Session}    ${Request Header}    Create Request Session

    TRY
        ${Response Status}    POST On Session
        ...    ${Session}
        ...    ${API_URL}
        ...    headers=${Request Header}
        ...    json=${json}

        Log To Console    ${Response Status}
        ${API Status}    Run Keyword And Return Status    Status Should Be    200    ${Response Status}

        IF    ${API Status} == True
            ${Full Response}    Set Variable    ${Response Status.json()}
            Log To Console    ${Full Response}
            Log To Console    Case-ID: ${Full Response}[ID]
        END
    EXCEPT
        Log To Console    api not working
    END

Start writing here...