• Lessons Home
Topics
Community
  1. Lessons
  2. Integration Fundamentals
  3. Callout Basics
  4. Status Codes

      Status Codes

      Status Codes

      Every response carries a number that says what happened: the status code. The
      number is not random. Its first digit names a family, and the family tells you
      whether the call worked, whether the request was wrong, or whether the service
      broke.

      The Families

      • 2xx means the request worked. The body holds the data you asked for.
      • 3xx means the answer is somewhere else. The service is pointing you at
        another address.
      • 4xx means the request was the problem: the resource was not found, the query
        was malformed, the key was refused.
      • 5xx means the service had the problem: it broke, or it is too busy, or it ran
        out of time.

      A family is a range, not a single value. 200, 201 and 204 are all successes,
      and 400, 401, 403 and 404 are all client errors. So compare the code with a
      range instead of with one number:

      Integer code = response.getStatusCode();
      if (code >= 200 && code < 300) {
      	// the request worked
      } else if (code >= 400 && code < 500) {
      	// the request was wrong
      } else if (code >= 500 && code < 600) {
      	// the service broke
      }
      

      The Response Is the Truth

      Read the status code off the response, never off the number you asked for. A
      service may answer with a code you did not ask for. DummyJSON answers a status
      code it does not support with 500, so a request for 100 comes back as a server
      error rather than as 100.

      Some Successes Have No Body

      A 204 is a success and it carries no body at all. Parsing an empty string
      throws System.JSONException, so check the status code first and read the
      body only when there is one to read.

      Common Mistakes

      The first mistake is comparing the status code with one value, so a 201 falls
      through and looks like a failure. The second is reading the body before
      checking the status code. The third is trusting the number you asked for
      instead of the code that came back.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In