# Comments · OpenAPI sample

A public GET request with an optional postId filter. The query value, curl command, and response example come from the OpenAPI source.

> Source: https://appgram.github.io/docsy/versions/current/es/api/comments  
> Endpoints: 1  
> API version: v1.0.0

See [How this OpenAPI sample works](/docsy/versions/current/es/guides/tutorials/openapi-ingestion) for the base setup.

### List comments for a post

Filter comments using a query parameter. Omit `postId` to list all comments. No API key is needed.

**`GET`** `/comments`

**Query parameters**

| Name | Type | Required | Description |

| --- | --- | --- | --- |

| `postId` | `integer` |  | Return only comments belonging to this post. |

**Request**

**cURL**

```bash
curl --request GET \
  --url 'https://jsonplaceholder.typicode.com/comments?postId=1'
```

**JavaScript · fetch**

```javascript
const response = await fetch("https://jsonplaceholder.typicode.com/comments?postId=1", {
  method: "GET",
  headers: {},
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.text());

```

**TypeScript · fetch**

```typescript
const response = await fetch("https://jsonplaceholder.typicode.com/comments?postId=1", {
  method: "GET",
  headers: {},
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.text());

```

**Node.js · fetch**

```javascript
const response = await fetch("https://jsonplaceholder.typicode.com/comments?postId=1", {
  method: "GET",
  headers: {},
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.text());

```

**Python · requests**

```python
import requests

response = requests.request(
    "GET",
    "https://jsonplaceholder.typicode.com/comments?postId=1",
    headers={},
    timeout=30,
)
response.raise_for_status()
print(response.text)

```

**Go · net/http**

```go
package main

import (
	"fmt"
	"net/http"
	"io"
)

func main() {

	url := "https://jsonplaceholder.typicode.com/comments?postId=1"

	req, _ := http.NewRequest("GET", url, nil)

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(string(body))

}
```

**Java · HttpClient**

```java
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://jsonplaceholder.typicode.com/comments?postId=1"))
    .method("GET", HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
```

**Kotlin · OkHttp**

```kotlin
// Requires OkHttp 4.x.
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody

fun main() {
  val request = Request.Builder()
    .url("https://jsonplaceholder.typicode.com/comments?postId=1")
    .method("GET", null)
    .build()
  OkHttpClient().newCall(request).execute().use { response ->
    println(response.body?.string())
  }
}

```

**C# · HttpClient**

```csharp
using System.Net.Http.Headers;
var client = new HttpClient();
var request = new HttpRequestMessage
{
    Method = HttpMethod.Get,
    RequestUri = new Uri("https://jsonplaceholder.typicode.com/comments?postId=1"),
};
using (var response = await client.SendAsync(request))
{
    response.EnsureSuccessStatusCode();
    var body = await response.Content.ReadAsStringAsync();
    Console.WriteLine(body);
}
```

**C · libcurl**

```c
CURL *hnd = curl_easy_init();

curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout);
curl_easy_setopt(hnd, CURLOPT_URL, "https://jsonplaceholder.typicode.com/comments?postId=1");

CURLcode ret = curl_easy_perform(hnd);
```

**C++ · libcurl**

```cpp
CURL *hnd = curl_easy_init();

curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout);
curl_easy_setopt(hnd, CURLOPT_URL, "https://jsonplaceholder.typicode.com/comments?postId=1");

CURLcode ret = curl_easy_perform(hnd);
```

**Rust · reqwest**

```rust
// Cargo: reqwest = "0.12", tokio = { version = "1", features = ["full"] }
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let response = reqwest::Client::new()
        .request(reqwest::Method::from_bytes("GET".as_bytes())?, "https://jsonplaceholder.typicode.com/comments?postId=1")
        .send().await?
        .error_for_status()?;
    println!("{}", response.text().await?);
    Ok(())
}

```

**Swift · URLSession**

```swift
import Foundation

var request = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/comments?postId=1")!)
request.httpMethod = "GET"
let (data, _) = try await URLSession.shared.data(for: request)
print(String(decoding: data, as: UTF8.self))

```

**Objective-C · NSURLSession**

```objectivec
#import <Foundation/Foundation.h>

int main(void) {
  @autoreleasepool {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://jsonplaceholder.typicode.com/comments?postId=1"]];
    request.HTTPMethod = @"GET";
    dispatch_semaphore_t done = dispatch_semaphore_create(0);
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
      if (error) NSLog(@"%@", error);
      else NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
      dispatch_semaphore_signal(done);
    }] resume];
    dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
  }
  return 0;
}

```

**Dart · http**

```dart
// Requires package:http in pubspec.yaml.
import 'package:http/http.dart' as http;

Future<void> main() async {
  final request = http.Request("GET", Uri.parse("https://jsonplaceholder.typicode.com/comments?postId=1"));
  request.headers.addAll({
  });
  final response = await request.send();
  print(await response.stream.bytesToString());
}

```

**PHP · cURL**

```php
<?php
$curl = curl_init('https://jsonplaceholder.typicode.com/comments?postId=1');
curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [],
]);
$response = curl_exec($curl);
if ($response === false) { throw new RuntimeException(curl_error($curl)); }
curl_close($curl);
echo $response;

```

**Ruby · Net::HTTP**

```ruby
require 'uri'
require 'net/http'

url = URI("https://jsonplaceholder.typicode.com/comments?postId=1")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = url.scheme == 'https'
request = Net::HTTPGenericRequest.new("GET", false, true, url.request_uri, {})
response = http.request(request)
puts response.body

```

**Scala · Java HttpClient**

```scala
import java.net.URI
import java.net.http.{HttpClient, HttpRequest, HttpResponse}

object Example extends App {
  val request = HttpRequest.newBuilder(URI.create("https://jsonplaceholder.typicode.com/comments?postId=1"))
    .method("GET", HttpRequest.BodyPublishers.noBody())
    .build()
  val response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString())
  println(response.body())
}

```

**Elixir · :httpc**

```elixir
:inets.start()
:ssl.start()
url = String.to_charlist("https://jsonplaceholder.typicode.com/comments?postId=1")
headers = []
http_options = [ssl: [verify: :verify_peer, cacerts: :public_key.cacerts_get(), customize_hostname_check: [match_fun: :public_key.pkix_verify_hostname_match_fun(:https)]]]
{:ok, {{_, status, _}, _, body}} = :httpc.request(:get, {url, headers}, http_options, [body_format: :binary])
IO.inspect(status)
IO.puts(body)

```

**Lua · Lua-cURL**

```lua
-- Requires Lua-cURL; libcurl retains its default TLS verification.
local curl = require('cURL')
local response = {}
local request = curl.easy {
  url = "https://jsonplaceholder.typicode.com/comments?postId=1",
  customrequest = "GET",
  httpheader = {
  },
  writefunction = function(chunk)
    response[#response + 1] = chunk
    return #chunk
  end
}
request:perform()
request:close()
print(table.concat(response))

```

**F# · HttpClient**

```fsharp
open System.Net.Http
open System.Text

use client = new HttpClient()
use request = new HttpRequestMessage(HttpMethod("GET"), "https://jsonplaceholder.typicode.com/comments?postId=1")
use response = client.SendAsync(request).GetAwaiter().GetResult()
printfn "%s" (response.Content.ReadAsStringAsync().GetAwaiter().GetResult())

```

**Visual Basic · HttpClient**

```visualbasic
Imports System.Net.Http
Imports System.Text

Module Example
  Sub Main()
    Using client As New HttpClient(), request As New HttpRequestMessage(New HttpMethod("GET"), "https://jsonplaceholder.typicode.com/comments?postId=1")
      Using response = client.SendAsync(request).GetAwaiter().GetResult()
        Console.WriteLine(response.Content.ReadAsStringAsync().GetAwaiter().GetResult())
      End Using
    End Using
  End Sub
End Module

```

**PowerShell · Invoke-RestMethod**

```powershell
$headers = @{
}
$response = Invoke-RestMethod -Method 'GET' -Uri 'https://jsonplaceholder.typicode.com/comments?postId=1' -Headers $headers
$response | ConvertTo-Json -Depth 20

```

**R · httr**

```r
library(httr)

headers <- setNames(c(), c())
response <- VERB("GET", "https://jsonplaceholder.typicode.com/comments?postId=1", add_headers(.headers = headers))
stop_for_status(response)
cat(content(response, as = "text", encoding = "UTF-8"))

```

**Response** — `200`

```json
[
  {
    "id": 1,
    "postId": 1,
    "name": "Example comment",
    "email": "reader@example.com",
    "body": "Example response content. Live comment text can differ."
  }
]
```
