0Pricing
AI Powered SaaS: Stripe + Auth + Billing + Deploy · Урок

Первые конечные точки API

Разработайте первые конечные точки API для базовых операций CRUD, демонстрируя получение, создание, обновление и удаление данных.

«Первые конечные точки API» — бесплатный урок AI Powered SaaS: Stripe + Auth + Billing + Deploy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения AI Powered SaaS: Stripe + Auth + Billing + Deploy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс AI Powered SaaS: Stripe + Auth + Billing + Deploy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What are API Endpoints?

When you interact with a web application, you're often using an Application Programming Interface (API). APIs allow different software systems to communicate with each other.

An API endpoint is a specific URL where an API can be accessed by a client. Think of it as a specific address you send requests to, to perform an action or get data.

  • URL Examples: /users, /products/123
  • Endpoints define the 'what' and 'where' of an API interaction.

Introducing CRUD Operations

Most applications need to manage data. The fundamental operations for data management are often summarized by the acronym CRUD:

  • Create: Adding new data.
  • Read: Retrieving existing data.
  • Update: Modifying existing data.
  • Delete: Removing data.

These operations map directly to common HTTP methods used in RESTful API design, allowing clients to perform actions on resources.

The 'Read' Operation (GET)

The Read operation, typically mapped to the HTTP GET method, is used to retrieve data from the server.

  • It's considered safe because it doesn't change the server's state.
  • It's idempotent, meaning making the same request multiple times has the same effect as making it once.

You use GET to fetch a list of resources (e.g., all tasks) or a specific resource by its identifier (e.g., a single task).

GET All Items: Example

To get a list of all resources, you'd typically use a GET request to the base endpoint for that resource type (e.g., /tasks).

Try running this simple Java code that simulates fetching all tasks from an in-memory list.

import java.util.ArrayList;
import java.util.List;

class Task {
    int id;
    String description;
    boolean completed;

    public Task(int id, String description, boolean completed) {
        this.id = id;
        this.description = description;
        this.completed = completed;
    }

    @Override
    public String toString() {
        return "Task{id=" + id + ", desc='" + description + "', done=" + completed + "}";
    }
}

public class Main {
    private static List<Task> tasks = new ArrayList<>();

    public static void main(String[] args) {
        // Setup initial data for this example
        tasks.clear(); // Clear previous state
        tasks.add(new Task(1, "Buy groceries", false));
        tasks.add(new Task(2, "Walk the dog", true));
        
        System.out.println("GET /tasks (All Tasks):");
        List<Task> allTasks = getAllTasks();
        allTasks.forEach(System.out::println);
    }

    // Simulates GET /tasks
    public static List<Task> getAllTasks() {
        return new ArrayList<>(tasks); // Return a copy
    }
}

GET Single Item: Example

To retrieve a specific resource, you append its unique identifier (like an ID) to the endpoint (e.g., /tasks/1).

This code simulates fetching a single task by its ID. Notice how it handles cases where the task might not be found.

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

class Task {
    int id;
    String description;
    boolean completed;

    public Task(int id, String description, boolean completed) {
        this.id = id;
        this.description = description;
        this.completed = completed;
    }

    @Override
    public String toString() {
        return "Task{id=" + id + ", desc='" + description + "', done=" + completed + "}";
    }
}

public class Main {
    private static List<Task> tasks = new ArrayList<>();

    public static void main(String[] args) {
        // Setup initial data for this example
        tasks.clear();
        tasks.add(new Task(1, "Pay bills", false));
        tasks.add(new Task(2, "Call friend", false));
        
        System.out.println("GET /tasks/1 (Single Task):");
        Optional<Task> taskById = getTaskById(1);
        taskById.ifPresentOrElse(
            task -> System.out.println("Found: " + task),
            () -> System.out.println("Task not found.")
        );

        System.out.println("\nGET /tasks/99 (Non-existent Task):");
        Optional<Task> nonExistentTask = getTaskById(99);
        nonExistentTask.ifPresentOrElse(
            task -> System.out.println("Found: " + task),
            () -> System.out.println("Task not found.")
        );
    }

    // Simulates GET /tasks/{id}
    public static Optional<Task> getTaskById(int id) {
        return tasks.stream()
                     .filter(t -> t.id == id)
                     .findFirst();
    }
}

The 'Create' Operation (POST)

The Create operation is typically handled by the HTTP POST method. It's used to send new data to the server to create a new resource.

  • It's generally not idempotent: sending the same POST request multiple times will usually create multiple identical resources.
  • The data for the new resource is sent in the request body.
  • A successful POST typically returns a 201 Created status code.

POST New Item: Example

To create a new task, you would send a POST request to the /tasks endpoint with the new task's details in the request body.

This code simulates creating new tasks and assigning them unique IDs.

import java.util.ArrayList;
import java.util.List;

class Task {
    int id;
    String description;
    boolean completed;

    public Task(int id, String description, boolean completed) {
        this.id = id;
        this.description = description;
        this.completed = completed;
    }

    @Override
    public String toString() {
        return "Task{id=" + id + ", desc='" + description + "', done=" + completed + "}";
    }
}

public class Main {
    private static List<Task> tasks = new ArrayList<>();
    private static int nextId = 1; // Reset for each example

    public static void main(String[] args) {
        tasks.clear();
        nextId = 1; // Ensure IDs start fresh
        
        System.out.println("POST /tasks (Create Task):");
        Task newTask1 = createTask("Write report");
        System.out.println("Created: " + newTask1);
        
        Task newTask2 = createTask("Schedule meeting");
        System.out.println("Created: " + newTask2);

        System.out.println("\nAll tasks after creation:");
        tasks.forEach(System.out::println);
    }

    // Simulates POST /tasks
    public static Task createTask(String description) {
        Task task = new Task(nextId++, description, false);
        tasks.add(task);
        return task;
    }
}

The 'Update' Operation (PUT)

The Update operation is commonly performed with the HTTP PUT method. It's used to modify an existing resource by replacing it entirely with new data.

  • PUT is idempotent: sending the same PUT request multiple times will have the same effect as a single request.
  • You typically send a PUT request to a specific resource endpoint (e.g., /tasks/1) with the updated data in the body.
  • Note: PATCH is another update method for partial modifications, but PUT is for full replacement.

PUT Existing Item: Example

To update an existing task, you'd make a PUT request to /tasks/{id}, sending the complete new state of the task.

This code demonstrates how a task's description and completion status can be updated.

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

class Task {
    int id;
    String description;
    boolean completed;

    public Task(int id, String description, boolean completed) {
        this.id = id;
        this.description = description;
        this.completed = completed;
    }

    @Override
    public String toString() {
        return "Task{id=" + id + ", desc='" + description + "', done=" + completed + "}";
    }
}

public class Main {
    private static List<Task> tasks = new ArrayList<>();

    public static void main(String[] args) {
        // Setup initial data
        tasks.clear();
        tasks.add(new Task(1, "Read book", false));
        tasks.add(new Task(2, "Exercise", false));
        
        System.out.println("Initial tasks:");
        tasks.forEach(System.out::println);

        System.out.println("\nPUT /tasks/1 (Update Task):");
        Task updatedTask = updateTask(1, "Finish reading 'Clean Code'", true);
        if (updatedTask != null) {
            System.out.println("Updated: " + updatedTask);
        } else {
            System.out.println("Task 1 not found for update.");
        }

        System.out.println("\nAll tasks after update:");
        tasks.forEach(System.out::println);
    }

    // Helper to find task (similar to GET by ID)
    public static Optional<Task> getTaskById(int id) {
        return tasks.stream()
                     .filter(t -> t.id == id)
                     .findFirst();
    }

    // Simulates PUT /tasks/{id}
    public static Task updateTask(int id, String newDescription, boolean newCompleted) {
        Optional<Task> existingTaskOpt = getTaskById(id);
        if (existingTaskOpt.isPresent()) {
            Task existingTask = existingTaskOpt.get();
            existingTask.description = newDescription;
            existingTask.completed = newCompleted;
            return existingTask;
        }
        return null; // Task not found
    }
}

The 'Delete' Operation (DELETE)

The Delete operation is handled by the HTTP DELETE method. It's used to remove a specific resource from the server.

  • DELETE is also idempotent: deleting a resource multiple times has the same effect as deleting it once (it's gone).
  • You send a DELETE request to the specific resource's endpoint (e.g., /tasks/2).
  • A successful DELETE typically returns a 204 No Content status code.

This code simulates removing a task by its ID from our in-memory list.

import java.util.ArrayList;
import java.util.List;

class Task {
    int id;
    String description;
    boolean completed;

    public Task(int id, String description, boolean completed) {
        this.id = id;
        this.description = description;
        this.completed = completed;
    }

    @Override
    public String toString() {
        return "Task{id=" + id + ", desc='" + description + "', done=" + completed + "}";
    }
}

public class Main {
    private static List<Task> tasks = new ArrayList<>();

    public static void main(String[] args) {
        // Setup initial data
        tasks.clear();
        tasks.add(new Task(1, "Plan vacation", false));
        tasks.add(new Task(2, "Book flights", false));
        tasks.add(new Task(3, "Pack bags", false));
        
        System.out.println("Initial tasks:");
        tasks.forEach(System.out::println);

        System.out.println("\nDELETE /tasks/2 (Delete Task):");
        boolean deleted = deleteTask(2);
        System.out.println("Task 2 deleted: " + deleted);

        System.out.println("\nAll tasks after deletion:");
        tasks.forEach(System.out::println);

        System.out.println("\nDELETE /tasks/99 (Non-existent Task):");
        boolean deletedNonExistent = deleteTask(99);
        System.out.println("Task 99 deleted: " + deletedNonExistent);
    }

    // Simulates DELETE /tasks/{id}
    public static boolean deleteTask(int id) {
        return tasks.removeIf(t -> t.id == id);
    }
}

Quick Check: HTTP Methods

Which HTTP method is typically used to add new data to a server, and which is used to retrieve existing data?

Recap & What's Next

You've learned the fundamentals of API endpoints and the four core CRUD operations: Create, Read, Update, and Delete. Each operation typically maps to a specific HTTP method (POST, GET, PUT, DELETE) and interacts with a resource at a defined endpoint.

  • GET: Fetch data (all or by ID).
  • POST: Create new data.
  • PUT: Update/replace existing data.
  • DELETE: Remove data.

Understanding these basic building blocks is crucial for designing and interacting with any API. In upcoming lessons, we'll dive deeper into how these endpoints connect to databases and how to secure them.

Часто задаваемые вопросы

Урок «Первые конечные точки API» бесплатный?

Да — полный текст урока «Первые конечные точки API» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс AI Powered SaaS: Stripe + Auth + Billing + Deploy, подпишись на CoddyKit PRO. Курс AI Powered SaaS: Stripe + Auth + Billing + Deploy содержит 4 уроков всего.

Чему я научусь в уроке «Первые конечные точки API»?

Разработайте первые конечные точки API для базовых операций CRUD, демонстрируя получение, создание, обновление и удаление данных. Ты практикуешь AI Powered SaaS: Stripe + Auth + Billing + Deploy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Предыдущий опыт не требуется. AI Powered SaaS: Stripe + Auth + Billing + Deploy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Первые конечные точки API»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Да. Каждый урок AI Powered SaaS: Stripe + Auth + Billing + Deploy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Принципы проектирования RESTful API
  2. Схема базы данных и ORM
  3. Первые конечные точки API
  4. Разбиение, фильтрация и сортировка данных API
← Назад к AI Powered SaaS: Stripe + Auth + Billing + Deploy