Making POST, PUT, and DELETE Requests¶
You've already learned how to make GET requests to fetch data. Now let's learn how to send data to web services using POST, PUT, and DELETE requests.
These are the methods you need when:
- POST - Create something new (like posting a comment)
- PUT - Update something (like changing your profile)
- DELETE - Remove something (like deleting a post)
Making a POST Request with JSON¶
Here's an example that sends a new user to a test API:
Making a PUT Request (Update)¶
PUT requests are similar to POST, but they update existing data:
Making a DELETE Request¶
DELETE requests remove data:
Adding Request Headers¶
Many APIs need special headers. Here's how to add them:
client := TFPHTTPClient.Create(nil);
try
{ Add headers }
client.AddHeader('Content-Type', 'application/json');
client.AddHeader('User-Agent', 'MyApp/1.0');
client.AddHeader('Accept', 'application/json');
{ Now make your request }
response := client.SimplePost(url, jsonData);
finally
client.Free;
end;
Common Headers Explained¶
- Content-Type - Tells the server what format you're sending
application/json- You're sending JSON-
application/x-www-form-urlencoded- You're sending form data -
Authorization - Sends your credentials
-
Used for APIs that need authentication (we'll cover this in the next article)
-
User-Agent - Tells the server what program is making the request
-
Good practice to set this
-
Accept - Tells the server what format you want back
application/json- You want JSON responses
Handling Responses¶
After making a request, you get back a response. You might want to check if it worked:
var
response: string;
responseCode: integer;
begin
response := client.SimplePost(url, jsonString);
responseCode := client.ResponseStatusCode;
if responseCode = 201 then
WriteLn('Success! Created new resource')
else if responseCode = 200 then
WriteLn('Success!')
else if responseCode = 400 then
WriteLn('Bad request - check your data')
else if responseCode = 404 then
WriteLn('Not found')
else if responseCode >= 500 then
WriteLn('Server error');
end;
Common Status Codes¶
- 200 - OK (success)
- 201 - Created (new resource made)
- 400 - Bad Request (your data is wrong)
- 401 - Unauthorized (need authentication)
- 404 - Not Found (resource doesn't exist)
- 500 - Server Error
Testing Your Requests¶
You can test these requests with jsonplaceholder.typicode.com - a free test API. It accepts POST, PUT, and DELETE requests without needing authentication.
Key Differences from GET¶
- GET just fetches data
- POST sends new data to create something
- PUT sends data to update something
- DELETE removes data
All three need special headers to work properly with JSON APIs.