बैचिंग अनुरोध

इस दस्तावेज़ में बताया गया है कि एपीआई कॉल को एक साथ कैसे बैच बनाकर प्रोसेस करना है. इससे, क्लाइंट को बनाए जाने वाले एचटीटीपी कनेक्शन की संख्या कम होगी.

यह दस्तावेज़ खास तौर पर, एचटीटीपी अनुरोध भेजकर बैच अनुरोध करने के बारे में है. इसके बजाय, अगर आप बैच अनुरोध करने के लिए Google क्लाइंट लाइब्रेरी का इस्तेमाल कर रहे हैं, तो क्लाइंट लाइब्रेरी का दस्तावेज़ देखें.

खास जानकारी

आपका क्लाइंट हर एचटीटीपी कनेक्शन से, एक तय ओवरहेड बनाता है. Google Classroom API पर एक साथ कई एपीआई कॉल करने की सुविधा उपलब्ध है. इससे आपका क्लाइंट एक ही एचटीटीपी अनुरोध में कई एपीआई कॉल कर सकता है.

उन स्थितियों के उदाहरण जहां आपको एक साथ कई अनुरोध भेजने की सुविधा का इस्तेमाल करना चाहिए:

  • बहुत सारे कोर्स के लिए नामावलियां फ़ेच की जा रही हैं.
  • एक साथ कई कोर्स बनाने या अपडेट करने की सुविधा.
  • बहुत सारे कोर्स की नामावली जोड़ना.
  • बड़ी संख्या में उपयोगकर्ताओं के लिए कोर्स की सूचियां हासिल की जा रही हैं.

हर मामले में, हर कॉल को अलग-अलग भेजने के बजाय, उन्हें एक ही एचटीटीपी अनुरोध में एक साथ ग्रुप किया जा सकता है. सभी अनुरोध एक ही Google API पर भेजे जाने चाहिए.

एक बार में ज़्यादा से ज़्यादा 50 कॉल किए जा सकते हैं. अगर आपको इससे ज़्यादा कॉल करने हैं, तो एक साथ कई अनुरोध करें.

ध्यान दें: Google Classroom API के लिए बैच सिस्टम, OData बैच प्रोसेसिंग सिस्टम जैसे ही सिंटैक्स का इस्तेमाल करता है. हालांकि, इसके सिमेंटिक्स अलग होते हैं.

बैच की जानकारी

एक साथ कई अनुरोध भेजने के अनुरोध में, एक ही एचटीटीपी अनुरोध में कई एपीआई कॉल शामिल होते हैं. यह अनुरोध एपीआई डिस्कवरी दस्तावेज़ में दिए गए batchPath पर भेजा जा सकता है. डिफ़ॉल्ट पाथ /batch/api_name/api_version है. इस सेक्शन में बैच सिंटैक्स के बारे में पूरी जानकारी दी गई है. बाद में, इसका एक उदाहरण दिया गया है.

ध्यान दें: बैच में भेजे गए n अनुरोधों का एक सेट, इस्तेमाल करने की आपकी सीमा में n अनुरोधों के तौर पर गिना जाता है, न कि एक अनुरोध के तौर पर. प्रोसेस करने से पहले, एक साथ कई अनुरोधों को अलग-अलग अनुरोधों में बांट दिया जाता है.

बैच अनुरोध का फ़ॉर्मैट

बैच रिक्वेस्ट, एक स्टैंडर्ड एचटीटीपी अनुरोध होता है. इसमें multipart/mixed कॉन्टेंट टाइप का इस्तेमाल करके, कई Google Classroom एपीआई कॉल शामिल होते हैं. उस मुख्य एचटीटीपी अनुरोध में, हर हिस्से में एक नेस्ट किया गया एचटीटीपी अनुरोध होता है.

हर हिस्से अपने Content-Type: application/http एचटीटीपी हेडर से शुरू होता है. इसमें एक वैकल्पिक Content-ID हेडर भी हो सकता है. हालांकि, पार्ट हेडर सिर्फ़ हिस्से की शुरुआत को मार्क करने के लिए होते हैं; वे नेस्ट किए गए अनुरोध से अलग होते हैं. जब सर्वर बैच अनुरोध को अलग-अलग अनुरोधों में खोलता है, तो पार्ट हेडर को नज़रअंदाज़ कर दिया जाता है.

हर हिस्से का मुख्य हिस्सा अपने-आप में एक एचटीटीपी अनुरोध होता है. इसका अपना वर्ब, यूआरएल, हेडर, और मुख्य हिस्सा होता है. एचटीटीपी अनुरोध में सिर्फ़ यूआरएल का पाथ वाला हिस्सा शामिल होना चाहिए. एक साथ कई अनुरोधों में पूरे यूआरएल की अनुमति नहीं है.

Content-Type जैसे Content- हेडर को छोड़कर, आउटर बैच अनुरोध के एचटीटीपी हेडर, बैच में हर अनुरोध पर लागू होते हैं. अगर किसी एचटीटीपी हेडर को आउटर अनुरोध और व्यक्तिगत कॉल, दोनों में सेट किया जाता है, तो आउटर बैच रिक्वेस्ट हेडर की वैल्यू की जगह व्यक्तिगत कॉल हेडर की वैल्यू लागू हो जाएगी. किसी एक कॉल के हेडर सिर्फ़ उस कॉल पर लागू होते हैं.

उदाहरण के लिए, अगर आप किसी खास कॉल के लिए ऑथराइज़ेशन हेडर देते हैं, तो वह हेडर सिर्फ़ उस कॉल पर लागू होता है. अगर आप बाहरी अनुरोध के लिए ऑथराइज़ेशन हेडर देते हैं, तो वह हेडर सभी कॉल पर लागू होता है. ऐसा तब तक होता है, जब तक कि वे अपने ऑथराइज़ेशन हेडर से इसे ओवरराइड नहीं कर देते.

जब सर्वर को बैच किया गया अनुरोध मिलता है, तो वह हर हिस्से पर बाहरी अनुरोध के क्वेरी पैरामीटर और हेडर (जैसा उचित हो) लागू करता है और फिर हर हिस्से को एक अलग एचटीटीपी अनुरोध की तरह मानता है.

बैच में किए गए अनुरोध का जवाब

सर्वर से मिलने वाला रिस्पॉन्स, multipart/mixed कॉन्टेंट टाइप वाला सिंगल स्टैंडर्ड एचटीटीपी रिस्पॉन्स होता है. हर हिस्सा, बैच में भेजे गए अनुरोध में से किसी एक अनुरोध का जवाब होता है. यह रिस्पॉन्स के क्रम में ही होता है.

अनुरोध के हिस्सों की तरह, जवाब के हर हिस्से में पूरा एचटीटीपी रिस्पॉन्स होता है. इसमें स्टेटस कोड, हेडर, और मुख्य हिस्सा शामिल होता है. अनुरोध के हिस्सों की तरह, रिस्पॉन्स वाले हर हिस्से से पहले एक Content-Type हेडर होता है. यह हेडर, हिस्से की शुरुआत के बारे में बताता है.

अगर अनुरोध के किसी हिस्से में Content-ID हेडर है, तो रिस्पॉन्स से जुड़े हिस्से का Content-ID हेडर मेल खाता है. साथ ही, स्ट्रिंग response- के पहले मूल वैल्यू होती है, जैसा कि यहां दिए गए उदाहरण में दिखाया गया है.

ध्यान दें: सर्वर किसी भी क्रम में आपको कॉल कर सकता है. उनके एक्ज़ीक्यूट होने के क्रम में उनकी गिनती न करें जिस क्रम में आपने उन्हें बताया है. अगर आपको यह पक्का करना है कि दिए गए ऑर्डर में दो कॉल हों, तो उन्हें एक ही अनुरोध में नहीं भेजा जा सकता. इसके बजाय, पहला अनुरोध खुद ही भेजें. इसके बाद, दूसरा कॉल भेजने से पहले, पहले वाले कॉल के जवाब का इंतज़ार करें.

उदाहरण

नीचे दिए गए उदाहरण में, Google Classroom API की मदद से बैच में अनुरोध भेजने का तरीका बताया गया है.

बैच अनुरोध का उदाहरण

POST https://classroom.googleapis.com/batch HTTP/1.1
Authorization: Bearer your_auth_token
Content-Type: multipart/mixed; boundary=batch_foobarbaz
Content-Length: total_content_length

--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
MIME-Version: 1.0
Content-ID: <item1:12930812@classroom.example.com>

PATCH /v1/courses/134529639?updateMask=name HTTP/1.1
Content-Type: application/json; charset=UTF-8
Authorization: Bearer your_auth_token

{
  "name": "Course 1"
}
--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
MIME-Version: 1.0
Content-ID: <item2:12930812@classroom.example.com>

PATCH /v1/courses/134529901?updateMask=section HTTP/1.1
Content-Type: application/json; charset=UTF-8
Authorization: Bearer your_auth_token
{
  "section": "Section 2"
}
--batch_foobarbaz--

बैच रिस्पॉन्स का उदाहरण

यह पिछले सेक्शन में उदाहरण के तौर पर दिए गए अनुरोध का जवाब है.

HTTP/1.1 200
Content-Length: response_total_content_length
Content-Type: multipart/mixed; boundary=batch_foobarbaz

--batch_foobarbaz
Content-Type: application/http
Content-ID: <response-item1:12930812@classroom.example.com>

HTTP/1.1 200 OK
Content-Type application/json
Content-Length: response_part_1_content_length

{
  "id": "134529639",
  "name": "Course 1",
  "section": "Section 1",
  "ownerId": "116269102540619633451",
  "creationTime": "2015-06-25T14:23:56.535Z",
  "updateTime": "2015-06-25T14:33:06.583Z",
  "enrollmentCode": "6paeflo",
  "courseState": "PROVISIONED",
  "alternateLink": "http://classroom.google.com/c/MTM0NTI5NjM5"
}
--batch_foobarbaz
Content-Type: application/http
Content-ID: <response-item2:12930812@classroom.example.com>

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: response_part_2_content_length

{
  "id": "134529901",
  "name": "Course 1",
  "section": "Section 2",
  "ownerId": "116269102540619633451",
  "creationTime": "2015-06-25T14:23:08.761Z",
  "updateTime": "2015-06-25T14:33:06.490Z",
  "enrollmentCode": "so75ha5",
  "courseState": "PROVISIONED",
  "alternateLink": "http://classroom.google.com/c/MTM0NTI5OTAx"
}
--batch_foobarbaz--

क्लाइंट लाइब्रेरी का इस्तेमाल करना

नीचे दिए गए कोड सैंपल, Google API क्लाइंट लाइब्रेरी का इस्तेमाल करके बैच अनुरोध करने का तरीका बताते हैं. लाइब्रेरी इंस्टॉल करने और उन्हें सेट अप करने के तरीके के बारे में ज़्यादा जानकारी के लिए, संबंधित क्विकस्टार्ट गाइड देखें.

.NET

classroom/snippets/Classroomsnippets/BatchAddछात्रs.cs
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Requests;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ClassroomSnippets
{
    // Class to demonstrate the use of Classroom Batch Add Students API
    public class BatchAddStudents
    {
        /// <summary>
        /// Add multiple students in a specified course.
        /// </summary>
        /// <param name="courseId">Id of the course to add students.</param>
        /// <param name="studentEmails">Email address of the students.</param>
        public static void ClassroomBatchAddStudents(string courseId,
            List<string> studentEmails)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(ClassroomService.Scope.ClassroomRosters);

                // Create Classroom API service.
                var service = new ClassroomService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Classroom Snippets"
                });

                var batch = new BatchRequest(service, "https://classroom.googleapis.com/batch");
                BatchRequest.OnResponse<Student> callback = (student, error, i, message) =>
                {
                    if (error != null)
                    {
                        Console.WriteLine("Error adding student to the course: {0}", error.Message);
                    }
                    else
                    {
                        Console.WriteLine("User '{0}' was added as a student to the course.",
                            student.Profile.Name.FullName);
                    }
                };
                foreach (var studentEmail in studentEmails)
                {
                    var student = new Student() {UserId = studentEmail};
                    var request = service.Courses.Students.Create(student, courseId);
                    batch.Queue<Student>(request, callback);
                }

                Task.WaitAll(batch.ExecuteAsync());
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is GoogleApiException)
                {
                    Console.WriteLine("Course does not exist.");
                }
                else
                {
                    throw;
                }
            }
        }
    }
}

Java

classroom/snippets/src/main/java/BatchAddछात्रs.java
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.classroom.Classroom;
import com.google.api.services.classroom.ClassroomScopes;
import com.google.api.services.classroom.model.Student;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/* Class to demonstrate the use of Classroom Batch Add Students API */
public class BatchAddStudents {

  /* Scopes required by this API call. If modifying these scopes, delete your previously saved
  tokens/ folder. */
  static ArrayList<String> SCOPES =
      new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS));

  /**
   * Add multiple students in a specified course.
   *
   * @param courseId - Id of the course to add students.
   * @param studentEmails - Email address of the students.
   * @throws IOException - if credentials file not found.
   * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
   */
  public static void batchAddStudents(String courseId, List<String> studentEmails)
      throws GeneralSecurityException, IOException {

    // Create the classroom API client.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Classroom service =
        new Classroom.Builder(
                HTTP_TRANSPORT,
                GsonFactory.getDefaultInstance(),
                ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES))
            .setApplicationName("Classroom samples")
            .build();

    BatchRequest batch = service.batch();
    JsonBatchCallback<Student> callback =
        new JsonBatchCallback<>() {
          public void onSuccess(Student student, HttpHeaders responseHeaders) {
            System.out.printf(
                "User '%s' was added as a student to the course.\n",
                student.getProfile().getName().getFullName());
          }

          public void onFailure(GoogleJsonError error, HttpHeaders responseHeaders) {
            System.out.printf("Error adding student to the course: %s\n", error.getMessage());
          }
        };
    for (String studentEmail : studentEmails) {
      Student student = new Student().setUserId(studentEmail);
      service.courses().students().create(courseId, student).queue(batch, callback);
    }
    batch.execute();
  }
}

129

Classroom/snippets/src/ClassroomClassroomAddछात्रs.php
use Google\Client;
use Google\Service\Classroom;
use Google\Service\Classroom\Student;
use Google\Service\Exception;

function batchAddStudents($courseId, $studentEmails)
{
    /* Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity for
     guides on implementing OAuth2 for your application. */
    $client = new Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope("https://www.googleapis.com/auth/classroom.profile.emails");
    $service = new Classroom($client);
    $service->getClient()->setUseBatch(true);
    //create batch
    $batch = $service->createBatch();
    foreach ($studentEmails as $studentEmail) {
        $student = new Student([
            'userId' => $studentEmail
        ]);
        $request = $service->courses_students->create($courseId, $student);
        $requestId = $studentEmail;
        $batch->add($request, $requestId);
    }
    //executing request
    $results = $batch->execute();
    foreach ($results as $responseId => $student) {
        $studentEmail = substr($responseId, strlen('response-') + 1);
        if ($student instanceof Exception) {
            $e = $student;
            printf("Error adding user '%s' to the course: %s\n", $studentEmail,
                $e->getMessage());
        } else {
            printf("User '%s' was added as a student to the course.\n",
                $student->profile->name->fullName, $courseId);
        }
    }
    $service->getClient()->setUseBatch(false);
    return $results;
}

Python

course_id = '123456'
student_emails = ['alice@example.edu', 'bob@example.edu']
def callback(request_id, response, exception):
    if exception is not None:
        print 'Error adding user "{0}" to the course course: {1}'.format(
            request_id, exception)
    else:
        print 'User "{0}" added as a student to the course.'.format(
            response.get('profile').get('name').get('fullName'))
batch = service.new_batch_http_request(callback=callback)
for student_email in student_emails:
    student = {
        'userId': student_email
    }
    request = service.courses().students().create(courseId=course_id,
                                                  body=student)
    batch.add(request, request_id=student_email)
batch.execute(http=http)