How to Create a REST API in Python and Java
Learn how to create a REST API in Python and Java, design resource-based endpoints, handle HTTP requests, test with Postman, and document your API.
What a REST API Does
To create a REST API, define your resources, map them to URLs, and write server code that handles HTTP requests. Then test each endpoint and document its inputs and outputs. You can build the same basic API in Python or Java, though each language uses different tools.
A REST API lets one program ask another for data or actions over HTTP. REST stands for Representational State Transfer. In practice, an API often sends data as JSON, a format that is easy for many programs to read. Some systems also support XML.
Think of a task app with a collection of tasks. A client can fetch the list, add a task, change one, or remove one. The API defines the URLs and request rules for those actions. The server checks each request, runs the needed logic, and returns a response.
Keep the first version small. A single resource with four operations is enough to learn the core design.
Build Around Resources and HTTP Rules
REST uses a client-server model. The client sends a request, and the server handles it. This split lets a web page, phone app, or other service use the same API.
REST is also stateless. Each request must carry the details the server needs, such as an ID or sign-in token. The server should not rely on memory of the client's last request. This makes requests easier to scale across servers.
Shape URLs around resources, not actions. For a task service, use /tasks for the collection and /tasks/42 for one task. Let the HTTP method state what the client wants to do.
- GET /tasks returns the task list.
- GET /tasks/42 returns one task.
- POST /tasks adds a task from the request body.
- PUT /tasks/42 replaces or updates task 42.
- DELETE /tasks/42 removes task 42.
Use clear status codes too. A successful read often returns 200, while a new record can return 201. Use 400 for bad input and 404 when a resource does not exist.
Good names make an API easier to use.

Plan the API Before You Code
Start by listing the resources your app needs. For a task app, a task might have an ID, title, and done flag. Decide which fields clients can send and which fields the server creates, such as the ID.
Next, write down each endpoint, its method, and its expected response. For example, POST /tasks could accept {"title":"Buy milk"} and return a new task with an ID. Define what happens when the title is missing or too long.
Choose a storage method for the first version. A list in memory works for a demo, but its data disappears when the server stops. A database is a better fit when records must last or several users share the service.
Then choose a framework and set up a project. Python developers can use Flask for a small service. Java developers can use Spring Boot, which provides tools for building web services. Install the framework, add a test client, and keep secrets out of source files.
Make one endpoint work before adding the rest.

Create a REST API in Python
Here is a small Flask example. It keeps records in memory, so use it to learn request flow rather than to store real user data. Install Flask in a virtual environment, then place this code in app.py.
from flask import Flask, request, jsonify
app = Flask(__name__)
tasks = []
@app.get('/tasks')
def list_tasks():
return jsonify(tasks)
@app.post('/tasks')
def add_task():
data = request.get_json()
if not data or not data.get('title'):
return jsonify({'error': 'title is required'}), 400
task = {'id': len(tasks) + 1, 'title': data['title'], 'done': False}
tasks.append(task)
return jsonify(task), 201
These routes show the key server-side steps. Flask matches the method and URL, reads the JSON body, checks the title, updates the data, and sends JSON back. Add routes for one task, then check for missing IDs before changing or deleting records.
Run the app with Flask's development server, then send a POST request with a JSON body. For a real service, use a database, limit accepted fields, and avoid exposing debug details to users. See the Flask quickstart documentation for the framework's request and route features.

Create a REST API in Java
For Java, Spring Boot can map HTTP requests to methods in a controller. Create a project with Spring Web, then define a Task class and a controller. The example below shows the route shape; a real app should use a service and database instead of a temporary list.
@RestController
@RequestMapping("/tasks")
class TaskController {
private final List<Task> tasks = new ArrayList<>();
@GetMapping
List<Task> all() { return tasks; }
@PostMapping
ResponseEntity<Task> add(@RequestBody Task task) {
tasks.add(task);
return ResponseEntity.status(201).body(task);
}
}
The annotations bind routes to Java methods. Spring reads the request body into a Task object and turns the return value into a response. Add checks for required fields before saving. Return a useful error when input fails, rather than letting a server fault expose internal details.
Spring can also support validation rules and shared error handling. Keep route code focused on HTTP tasks, and place business rules in a service class. The Spring REST service guide walks through a working setup and its controller pattern.

Test Requests and Responses
Use Postman to send requests without building a client app first. Create a request for each method, set the URL, and add a JSON body for POST or PUT. Check both the status code and the response body.
Test normal cases and failure cases. Try creating a task with a title, then try an empty body. Fetch an ID that exists and one that does not. Confirm that DELETE removes the right record and that repeated calls behave as your design expects.
- Start the local server and note its base URL.
- Send GET /tasks and check for a list response.
- Send POST /tasks with a valid JSON body.
- Send PUT and DELETE requests for the returned ID.
- Repeat with missing fields and unknown IDs.
Automated tests help catch changes that break old routes. Test the expected status, response fields, and stored data. Also check that invalid JSON or unsupported methods return clear errors.
Testing should cover more than the happy path.
Document and Protect the API
API documentation tells developers how to use each route without reading server code. For every endpoint, list its method, URL, required fields, response shape, and likely error codes. Add a short example request and response for common tasks.
Keep names and behavior consistent. Use one style for field names, return predictable errors, and validate all client input. Do not trust a value just because it came from your own app. Check IDs, field types, and allowed values on the server.
For a public or shared API, require sign-in where needed and use HTTPS. Give each user access only to the records they should see. Avoid returning passwords, secret keys, or internal error traces in responses.
Finally, keep the docs in step with the code. A route that changes without updated examples can waste hours for another developer. A small, well-tested API with clear docs is easier to extend than a large set of unclear endpoints.
Step-by-step
- 01 Choose resources
List the main things your API stores or serves. Define the fields for each resource.
- 02 Design routes and methods
Map resource collections and single items to clear URLs. Assign GET, POST, PUT, and DELETE where they fit.
- 03 Set up a framework
Pick Flask for a small Python service or Spring Boot for Java. Create a project and start a local server.
- 04 Write request handlers
Read request data, validate it, run server-side logic, and return JSON with a useful status code.
- 05 Test and document
Use Postman to test normal and error cases. Record each route, input, response, and likely error.
Frequently asked questions
- How do I create a REST API?
- Choose your resources, map them to URLs, and assign HTTP methods to each action. Build server routes, validate requests, return clear responses, then test and document them.
- How do I create a REST API in Python?
- Use a web framework such as Flask to map routes to Python functions. Read and validate request data, run the needed logic, and return JSON with a fitting status code.
- How do I create a REST API in Java?
- Spring Boot is a common choice for Java REST APIs. Define controller routes, bind request data to Java objects, validate it, and return the result with an appropriate status.
- Which HTTP methods should a REST API use?
- GET reads data, POST creates a resource, PUT updates or replaces one, and DELETE removes one. Match each method to a clear resource URL.
- How can I test a REST API?
- Use Postman to send requests and inspect status codes and response bodies. Test valid input, missing fields, unknown IDs, and each method your API supports.
- Why does a REST API need documentation?
- Documentation shows developers how to call each route and what to expect. Include methods, URLs, request fields, response examples, and common errors.
Related reading
What Does a Full Stack Software Developer Do?
See what full stack developers do, what they need to learn, and where the role can lead.
Is Ecommerce Growing, and Why Does It Matter?
Learn what drives ecommerce growth and where online stores can stumble.
What Is a Headless API, and How Does It Power eCommerce?
See how headless APIs link flexible storefronts with eCommerce back ends.