Search code examples
salesforcesalesforce-lightning

How to create a case in a Salesforce Account using REST API and python Script


I need some help. I need to create a case in a Account with all the details basically, all the fields, using REST API but it I am not able to figure out, how to insert a record for creating a case.

Could you please guide me, how to create a case using REST API in Salesforce?


Solution

  • Do you use a library such as https://pypi.org/project/simple-salesforce/0.3/ or do you need to craft the REST messages manually?

    You'd need to do it in 2 calls, login first (unless you have session id already) and then

    POST to 
        https://yourinstance.my.salesforce.com/services/data/v48.0/sobjects/Case
    with header 
        Authorization Bearer <session id goes here, sometimes called "access token" too>
    and body
        {
            "Subject": "Hello world",
            "Description": "Lorem ipsum dolor sit amet...",
            "Origin":"Web",
            "AccountId" :"0010g00001mbqU4"
        }
    

    should work like a charm (pass an account id value right for your org and you might have more fields to fill in).


    So now "only" how to log in. That's a bigger topic and depends if it's a backend thing or you'll have a human interacting with it, maybe logging in to SF and then coming back to your org. There's bit of reading on that (simpler if you'd use SOAP API to log in)

    For example this would work if I didn't redact all sensitive stuff

    POST to
        https://login.salesforce.com/services/oauth2/token
    with header
        Content-Type application/x-www-form-urlencoded
    and body
        grant_type=password
        &client_id=(ask your admin for "connected app")
        &client_secret=(ask your admin for "connected app")
        &username=redacted%40example.com
        &password=redacted
    

    Should return

    {
        "access_token": "<session id here, use it as Authorization header in next calls>",
        "instance_url": "<use this as base url of all next calls>",
        "id": "<call GET to this (with the Auth header) to learn more about user",
        "token_type": "Bearer",
        "issued_at": "1593684589157",
        "signature": "redacted"
    }
    

    Again - don't do it all by hand if you can, use one of Python libraries for Salesforce.