Skip to content

Commit caa3622

Browse files
authored
Merge pull request #45 from twitterdev/spaces
Add Spaces endpoints
2 parents a571f61 + b871412 commit caa3622

8 files changed

Lines changed: 395 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import java.io.IOException;
2+
import java.net.URISyntaxException;
3+
import java.util.ArrayList;
4+
5+
import org.apache.http.HttpEntity;
6+
import org.apache.http.HttpResponse;
7+
import org.apache.http.NameValuePair;
8+
import org.apache.http.client.HttpClient;
9+
import org.apache.http.client.config.CookieSpecs;
10+
import org.apache.http.client.config.RequestConfig;
11+
import org.apache.http.client.methods.HttpGet;
12+
import org.apache.http.client.utils.URIBuilder;
13+
import org.apache.http.impl.client.HttpClients;
14+
import org.apache.http.message.BasicNameValuePair;
15+
import org.apache.http.util.EntityUtils;
16+
17+
/*
18+
* Sample code to demonstrate the use of the Spaces lookup endpoint
19+
* */
20+
public class SpacesLookupDemo {
21+
22+
// To set your enviornment variables in your terminal run the following line:
23+
// export 'BEARER_TOKEN'='<your_bearer_token>'
24+
25+
public static void main(String args[]) throws IOException, URISyntaxException {
26+
String bearerToken = System.getenv("BEARER_TOKEN");
27+
if (null != bearerToken) {
28+
//Replace SPACE_ID with the ID of a Space
29+
String response = getSpaceById("SPACE_ID", bearerToken);
30+
System.out.println(response);
31+
} else {
32+
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
33+
}
34+
}
35+
36+
/*
37+
* This method calls the Spaces lookup endpoint with the ID passed to it as a query parameter
38+
* */
39+
private static String getSpaceById(String spaceId, String bearerToken) throws IOException, URISyntaxException {
40+
String searchResponse = null;
41+
42+
HttpClient httpClient = HttpClients.custom()
43+
.setDefaultRequestConfig(RequestConfig.custom()
44+
.setCookieSpec(CookieSpecs.STANDARD).build())
45+
.build();
46+
47+
URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/spaces");
48+
ArrayList<NameValuePair> queryParameters;
49+
queryParameters = new ArrayList<>();
50+
queryParameters.add(new BasicNameValuePair("ids", spaceId));
51+
uriBuilder.addParameters(queryParameters);
52+
53+
HttpGet httpGet = new HttpGet(uriBuilder.build());
54+
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
55+
httpGet.setHeader("User-Agent", "v2SpacesLookupJava");
56+
httpGet.setHeader("Content-Type", "application/json");
57+
58+
HttpResponse response = httpClient.execute(httpGet);
59+
HttpEntity entity = response.getEntity();
60+
if (null != entity) {
61+
searchResponse = EntityUtils.toString(entity, "UTF-8");
62+
}
63+
return searchResponse;
64+
}
65+
66+
}

Search-Spaces/search_spaces.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Lookup Spaces by ID
2+
// https://developer.twitter.com/en/docs/twitter-api/spaces/lookup
3+
4+
const needle = require('needle');
5+
6+
// The code below sets the bearer token from your environment variables
7+
// To set environment variables on macOS or Linux, run the export command below from the terminal:
8+
// export BEARER_TOKEN='YOUR-TOKEN'
9+
const token = process.env.BEARER_TOKEN;
10+
11+
const endpointUrl = `https://api.twitter.com/2/spaces/search`;
12+
13+
async function getRequest() {
14+
15+
// Edit query parameters below and specify a search query
16+
// optional params: host_ids,conversation_controls,created_at,creator_id,id,invited_user_ids,is_ticketed,lang,media_key,participants,scheduled_start,speaker_ids,started_at,state,title,updated_at
17+
const params = {
18+
'query': 'NBA', // Replace the value with your search term
19+
'space.fields': 'title,created_at',
20+
'expansions': 'creator_id'
21+
}
22+
23+
const res = await needle('get', endpointUrl, params, {
24+
headers: {
25+
"User-Agent": "v2SpacesSearchJS",
26+
"authorization": `Bearer ${token}`
27+
}
28+
})
29+
30+
if (res.body) {
31+
return res.body;
32+
} else {
33+
throw new Error('Unsuccessful request');
34+
}
35+
}
36+
37+
(async () => {
38+
39+
try {
40+
// Make request
41+
const response = await getRequest();
42+
console.dir(response, {
43+
depth: null
44+
});
45+
46+
} catch (e) {
47+
console.log(e);
48+
process.exit(-1);
49+
}
50+
process.exit();
51+
})();

Search-Spaces/search_spaces.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import requests
2+
import os
3+
import json
4+
5+
# To set your environment variables in your terminal run the following line:
6+
# export 'BEARER_TOKEN'='<your_bearer_token>'
7+
bearer_token = os.environ.get("BEARER_TOKEN")
8+
9+
search_url = "https://api.twitter.com/2/spaces/search"
10+
11+
search_term = 'NBA' # Replace this value with your search term
12+
13+
# Optional params: host_ids,conversation_controls,created_at,creator_id,id,invited_user_ids,is_ticketed,lang,media_key,participants,scheduled_start,speaker_ids,started_at,state,title,updated_at
14+
query_params = {'query': search_term, 'space.fields': 'title,created_at', 'expansions': 'creator_id'}
15+
16+
17+
def create_headers(bearer_token):
18+
headers = {
19+
"Authorization": "Bearer {}".format(bearer_token),
20+
"User-Agent": "v2SpacesSearchPython"
21+
}
22+
return headers
23+
24+
25+
def connect_to_endpoint(url, headers, params):
26+
response = requests.request("GET", search_url, headers=headers, params=params)
27+
print(response.status_code)
28+
if response.status_code != 200:
29+
raise Exception(response.status_code, response.text)
30+
return response.json()
31+
32+
33+
def main():
34+
headers = create_headers(bearer_token)
35+
json_response = connect_to_endpoint(search_url, headers, query_params)
36+
print(json.dumps(json_response, indent=4, sort_keys=True))
37+
38+
39+
if __name__ == "__main__":
40+
main()

Search-Spaces/search_spaces.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# This script uses your bearer token to authenticate and make a Spaces lookup request
2+
3+
require 'json'
4+
require 'typhoeus'
5+
6+
# The code below sets the bearer token from your environment variables
7+
# To set environment variables on macOS, run the export command below from the terminal:
8+
# export BEARER_TOKEN='YOUR-TOKEN'
9+
bearer_token = ENV["BEARER_TOKEN"]
10+
11+
# Endpoint URL
12+
spaces_search_url = "https://api.twitter.com/2/spaces/search"
13+
14+
# Replace this value with your search term
15+
query = "NBA"
16+
17+
# Add or remove parameters below to adjust the query and response fields within the payload
18+
# See docs for list of param options: https://developer.twitter.com/en/docs/twitter-api/spaces/search/api-reference
19+
query_params = {
20+
"query": query, # Required
21+
"space.fields": 'title,created_at',
22+
'expansions': 'creator_id'
23+
}
24+
25+
def get_space(url, bearer_token, query_params)
26+
options = {
27+
method: 'get',
28+
headers: {
29+
"User-Agent": "v2SpacesSearchRuby",
30+
"Authorization": "Bearer #{bearer_token}"
31+
},
32+
params: query_params
33+
}
34+
35+
request = Typhoeus::Request.new(url, options)
36+
response = request.run
37+
38+
return response
39+
end
40+
41+
response = get_space(spaces_search_url, bearer_token, query_params)
42+
puts response.code, JSON.pretty_generate(JSON.parse(response.body))
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import java.io.IOException;
2+
import java.net.URISyntaxException;
3+
import java.util.ArrayList;
4+
5+
import org.apache.http.HttpEntity;
6+
import org.apache.http.HttpResponse;
7+
import org.apache.http.NameValuePair;
8+
import org.apache.http.client.HttpClient;
9+
import org.apache.http.client.config.CookieSpecs;
10+
import org.apache.http.client.config.RequestConfig;
11+
import org.apache.http.client.methods.HttpGet;
12+
import org.apache.http.client.utils.URIBuilder;
13+
import org.apache.http.impl.client.HttpClients;
14+
import org.apache.http.message.BasicNameValuePair;
15+
import org.apache.http.util.EntityUtils;
16+
17+
/*
18+
* Sample code to demonstrate the use of the Spaces lookup endpoint
19+
* */
20+
public class SpacesLookupDemo {
21+
22+
// To set your enviornment variables in your terminal run the following line:
23+
// export 'BEARER_TOKEN'='<your_bearer_token>'
24+
25+
public static void main(String args[]) throws IOException, URISyntaxException {
26+
String bearerToken = System.getenv("BEARER_TOKEN");
27+
if (null != bearerToken) {
28+
//Replace SPACE_ID with the ID of a Space
29+
String response = getSpaceById("SPACE_ID", bearerToken);
30+
System.out.println(response);
31+
} else {
32+
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
33+
}
34+
}
35+
36+
/*
37+
* This method calls the Spaces lookup endpoint with the ID passed to it as a query parameter
38+
* */
39+
private static String getSpaceById(String spaceId, String bearerToken) throws IOException, URISyntaxException {
40+
String searchResponse = null;
41+
42+
HttpClient httpClient = HttpClients.custom()
43+
.setDefaultRequestConfig(RequestConfig.custom()
44+
.setCookieSpec(CookieSpecs.STANDARD).build())
45+
.build();
46+
47+
URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/spaces");
48+
ArrayList<NameValuePair> queryParameters;
49+
queryParameters = new ArrayList<>();
50+
queryParameters.add(new BasicNameValuePair("ids", spaceId));
51+
uriBuilder.addParameters(queryParameters);
52+
53+
HttpGet httpGet = new HttpGet(uriBuilder.build());
54+
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
55+
httpGet.setHeader("User-Agent", "v2SpacesLookupJava");
56+
httpGet.setHeader("Content-Type", "application/json");
57+
58+
HttpResponse response = httpClient.execute(httpGet);
59+
HttpEntity entity = response.getEntity();
60+
if (null != entity) {
61+
searchResponse = EntityUtils.toString(entity, "UTF-8");
62+
}
63+
return searchResponse;
64+
}
65+
66+
}

Spaces-Lookup/spaces_lookup.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Search for Tweets within the past seven days
2+
// https://developer.twitter.com/en/docs/twitter-api/tweets/search/quick-start/recent-search
3+
4+
const needle = require('needle');
5+
6+
// The code below sets the bearer token from your environment variables
7+
// To set environment variables on macOS or Linux, run the export command below from the terminal:
8+
// export BEARER_TOKEN='YOUR-TOKEN'
9+
const token = process.env.BEARER_TOKEN;
10+
11+
const endpointUrl = "https://api.twitter.com/2/tweets/counts/recent";
12+
13+
async function getRequest() {
14+
15+
// Edit query parameters below and specify a search query
16+
// optional params: start_time,end_time,since_id,until_id,next_token,granularity
17+
const params = {
18+
'query': 'from:twitterdev',
19+
'granularity': 'day'
20+
}
21+
22+
const res = await needle('get', endpointUrl, params, {
23+
headers: {
24+
"User-Agent": "v2RecentTweetCountsJS",
25+
"authorization": `Bearer ${token}`
26+
}
27+
})
28+
29+
if (res.body) {
30+
return res.body;
31+
} else {
32+
throw new Error('Unsuccessful request');
33+
}
34+
}
35+
36+
(async () => {
37+
38+
try {
39+
// Make request
40+
const response = await getRequest();
41+
console.dir(response, {
42+
depth: null
43+
});
44+
45+
} catch (e) {
46+
console.log(e);
47+
process.exit(-1);
48+
}
49+
process.exit();
50+
})();

Spaces-Lookup/spaces_lookup.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import requests
2+
import os
3+
import json
4+
5+
# To set your environment variables in your terminal run the following line:
6+
# export 'BEARER_TOKEN'='<your_bearer_token>'
7+
bearer_token = os.environ.get("BEARER_TOKEN")
8+
9+
search_url = "https://api.twitter.com/2/spaces"
10+
11+
# Optional params: host_ids,conversation_controls,created_at,creator_id,id,invited_user_ids,is_ticketed,lang,media_key,participants,scheduled_start,speaker_ids,started_at,state,title,updated_at
12+
query_params = {'ids': 'SPACE_ID', 'space.fields': 'title,created_at', 'expansions': 'creator_id'}
13+
14+
15+
def create_headers(bearer_token):
16+
headers = {
17+
"Authorization": "Bearer {}".format(bearer_token),
18+
"User-Agent": "v2SpacesLookupPython"
19+
}
20+
return headers
21+
22+
23+
def connect_to_endpoint(url, headers, params):
24+
response = requests.request("GET", search_url, headers=headers, params=params)
25+
print(response.status_code)
26+
if response.status_code != 200:
27+
raise Exception(response.status_code, response.text)
28+
return response.json()
29+
30+
31+
def main():
32+
headers = create_headers(bearer_token)
33+
json_response = connect_to_endpoint(search_url, headers, query_params)
34+
print(json.dumps(json_response, indent=4, sort_keys=True))
35+
36+
37+
if __name__ == "__main__":
38+
main()

0 commit comments

Comments
 (0)