-
Notifications
You must be signed in to change notification settings - Fork 5
/
openapi.yaml
2481 lines (1986 loc) · 81 KB
/
openapi.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
openapi: 3.0.0
info:
title: BulkSMS JSON REST API
description: >
## Overview
The JSON REST API allows you to submit and receive
[BulkSMS](https://www.bulksms.com/) messages. You can also get access to
past messages and see your account profile.
The base URL to use for this service is `https://api.bulksms.com/v1`. The
base URL cannot be used on its own; you must append a path that identifies
an operation and you may have to specify some path parameters as well.
[Click here](https://www.bulksms.com/developer/json/v1/#) to go to the main
BulkSMS developer site.
In order to give you an idea on how the API can be used, some JSON snippets
are provided below. Have a look at the [messages
section](https://www.bulksms.com/developer/json/v1/#) for more information.
Probably the most simple example
```
{
"to": "+27001234567",
"body": "Hello World!"
}
```
You can send unicode automatically using the `auto-unicode` query
parameter.
Alternatively, you can specify `UNICODE` for the `encoding` property in the
request body.
Please note: when `auto-unicode` is specified and the value of the
`encoding` property is `UNICODE`, the message will always be sent as
`UNICODE`.
Here is an example that sets the `encoding` explicitly
```
{
"to": "+27001234567",
"body": "Dobrá práce! Jak se máš?",
"encoding": "UNICODE"
}
```
You can also specify a from number
```
{
"from": "+27007654321",
"to": "+27001234567",
"body": "Hello World!"
}
```
Similar to above, but repliable
```
{
"from": { "type": "REPLIABLE" },
"to": "+27001234567",
"body": "Hello World!"
}
```
A message to a group called Everyone
```
{
"to": { "type": "GROUP", "name": "Everyone" },
"body": "Hello World!"
}
```
A message to multiple recipients
```
{
"to": ["+27001234567", "+27002345678", "+27003456789"],
"body": "Happy Holidays!"
}
```
Sending more than one message in the same request
```
[
{
"to": "+27001234567",
"body": "Hello World!"
},
{
"to": "+27002345678",
"body": "Hello Universe!"
}
]
```
**The insecure base URL `http://api.bulksms.com/v1` is deprecated** and may
in future result in a `301` redirect response, or insecure requests may be
rejected outright. Please use the secure (`https`) URI above.
### HTTP Content Type
All API methods expect requests to supply a `Content-Type` header with the
value `application/json`. All responses will have the `Content-Type` header
set to `application/json`.
### JSON Formatting
You are advised to format your JSON resources according to strict JSON
format rules. While the API does attempt to parse strictly invalid JSON
documents, doing so may lead to incorrect interpretation and unexpected
results.
Good JSON libraries will produce valid JSON suitable for submission, but if
you are manually generating the JSON text, be careful to follow the JSON
format. This include correct escaping of control characters and double
quoting of property names.
See the [JSON specification](https://tools.ietf.org/html/rfc4627) for
further information.
### Date Formatting
Dates are formatted according to ISO-8601, such as
`1970-01-01T10:00:00+01:00` for 1st January 1970, 10AM UTC+1.
See the [Wikipedia ISO 8601
reference](https://en.wikipedia.org/wiki/ISO_8601) for further information.
Specifically, calendar dates are formatted with the 'extended' format
`YYYY-MM-DD`. Basic format, week dates and ordinal dates are not supported.
Times are also formatted in the 'extended' format `hh:mm:ss`. Hours, minutes
and seconds are mandatory. Offset from UTC must be provided; this is to
ensure that there is no misunderstanding regarding times provided to the
API.
The format we look for is `yyyy-MM-ddThh:mm:ss[Z|[+-]hh:mm]`
Examples of valid date/times are`2011-12-31T12:00:00Z`
`2011-12-31T12:00:00+02:00`
### Entity Format Modifications
It is expected that over time some changes will be made to the request and
response formats of various methods available in the API.
Where possible, these will be implemented in a backwards compatible way.
To make this possible you are required to ignore unknown properties.
This enables the addition of information in response documents while
maintaining compatibility with older clients.
### Optional Request Entity Properties
There are many instances where requests can be made without having to
specify every single property allowable in the request format.
Any such optional properties are noted as such in the documentation and
their default value is noted.
version: 1.0.0
x-apisguru-categories:
- telecom
x-logo:
url: /developer/images/bulksms.png
x-origin:
- version: '3.0'
format: openapi
url: http://developer.bulksms.com/json/v1/swagger.yaml
x-providerName: bulksms.com
x-konfig-ignore:
potential-incorrect-type: true
servers:
- url: https://api.bulksms.com/v1
tags:
- name: Message
x-displayName: Messages
- name: Webhooks
- name: Blocked Numbers
- name: Profile
x-displayName: Profile
- name: Credits
- name: Attachments
paths:
/blocked-numbers:
get:
tags:
- Blocked Numbers
summary: List blocked numbers
operationId: BlockedNumbers_listRetrieval
parameters:
- description: >-
Records with an `id` that is greater or equal to min-id will be
returned. The default value is `0`. You can add 1 to an id that you
previously retrieved, to return subsequent records.
in: query
name: min-id
schema:
format: int32
type: integer
- description: >-
The maximum number of records to return. The default value is
`10000`. The value cannot be greater than 10000.
in: query
name: limit
schema:
format: int32
type: integer
responses:
'200':
description: A list of BlockedNumber objects
content:
application/json:
schema:
$ref: '#/components/schemas/BlockedNumber'
post:
tags:
- Blocked Numbers
summary: Create a blocked number
operationId: BlockedNumbers_createBlockedNumber
description: >
Blocked numbers are phone numbers to which your account is not permitted
to send messages.
The numbers can be created via this API, by a recipient replying with a
STOP message to one
of your previous SENT messages, or by a BulkSMS administrator.
Sending a message to a blocked number will result in the message being
assigned a status of
`FAILED.BLOCKED`. Messages sent to blocked numbers are billed to your
account.
requestBody:
description: 'Maximum size: `1000` items'
content:
application/json:
schema:
$ref: '#/components/schemas/BlockedNumbersCreateBlockedNumberRequest'
required: true
responses:
'200':
description: Empty body upon success
/credit/transfer:
post:
tags:
- Credits
summary: Transfer credits to another account
operationId: Credits_transferCreditsToAccount
description: >
Before you can use the transfer credits endpoint, the _credit-transfer
facility_ must be activated for your account. You can request
activation from `support@bulksms.com`.
The recipient must be an enabled account that uses the same currency as
your account.
requestBody:
description: |
Contains details of the transfer request.
content:
application/json:
schema:
$ref: '#/components/schemas/TransferEntry'
required: true
responses:
'200':
description: An empty body when the credits were transferred OK.
'400':
description: When the request fails validation checks.
'403':
description: >-
When there are not enough credits in your account or the credit
transfer facility is not activated.
/messages:
get:
tags:
- Message
summary: Retrieve Messages
operationId: Message_listRetrieval
description: >
Retrieve the messages you have sent or received.
Scheduled messages are available for retrieval only after the delivery
date.
All the parameters are optional. If a value is not supplied for
`filter`, the messages are not filtered.
Messages can be filtered by supplying query clauses in the `filter`
parameter. Each clause has the form `name=value` where `name` is the
name of a filter field and `value` is a valid value for that field. A
value for a field is optional. Include a clause for a field in the
filter only when there is a need to fetch messages that match some value
for that field.
For a numeric filter field, you can also use the less than operator
(`<`).
If present, the filter value must have at least one clause, but it can
contain a combination of clauses. Multiple clauses are separated with
the `&` symbol. Semantically, multiple clauses form a [logical
conjunction](https://en.wikipedia.org/wiki/Logical_conjunction).
For example, if you want to list all messages that were sent as part of
a particular submission, your filter contains two clauses and will look
something like this
```
type%3DSENT&submission.id%3D1-00000000000522347562
```
Because `filter` is a request parameter, it is important to note that
the value for this parameter must be *URL encoded*. In particular, the
`=` encodes to `%3D` and the `&` encodes to `%26`. Note that you do not
have to encode the `<` character.
Using the previous example to illustrate; after encoding and encasing
it, the clauses are transformed into a request that looks like this
```
GET
/v1/messages?filter=type%3DSENT%26submission.id%3D1-00000000000522347562
```
If the field name or the field value of a clause is not valid, a
[bad_request error](errors#bad-request) is returned instead of the usual
result. The `detail` field of this error provides more information
about the problem.
The table below lists the fields available for filtering
| Field | Type | Values | Note and example |
|-------|------|--------------------|------|
| id | Integer | Positive integer | Use the `id` field with
`<` (or with `>`) to fetch messages that are older (or newer) than those
that are already fetched. <br/>`filter=id<123456` |
| type | String | SENT, RECEIVED | SENT are Mobile
Terminating (MT) SMSs; RECEIVED are Mobile Originating (MO)
SMSs.<br/>`filter=type%3DSENT` |
| submission.id | String | |
`filter=submission.id%3D1-00000000000522347562` |
| status.type | String | ACCEPTED, SENT, DELIVERED, FAILED | See the
message `status.type` field for more information.
<br/>`filter=status.type%3DDELIVERED` |
| status.id| String | | See the message `status.id` field for more
information. `filter=status.id%3DFAILED.EXPIRED`|
| submission.date | String | Formatted Date | A fully specified date
(e.g. 2017-01-01T10:00:00+01:00). Use this field with `<=`, `<`, `>` or
`>=` to limit the values.
<br/>`filter=submission.date%3E%3D2017-01-01T10%3A00%3A00%2B01%3A00` |
| userSuppliedId | String | | Use a string value you specified in the
`userSuppliedId` property when you sent the message. Only `SENT`
messages will be retrieved. <br/>`filter=userSuppliedId%3Dacc009876` |
parameters:
- description: >-
The maximum number of messages that are returned. The default is
1000.
The value of `limit` is not a guarantee that a specific number of
messages will be in the response, even if there are more messages
available. Consider the case where you have 150 messages and you
specify `limit=50`. It is possible that only 49 messages will be
returned. The way to make sure that there are no more messages is
to submit a new call using the `id` filter field with the `<`
operator (described below).
in: query
name: limit
required: false
schema:
format: int
type: number
- description: See the message filtering for more information.
in: query
name: filter
schema:
type: string
- description: >
The default value is DESCENDING
If the `sortOrder` is DESCENDING, the newest messages be first in
the result. ASCENDING places the oldest messages on top of the
response.
in: query
name: sortOrder
schema:
enum:
- ASCENDING
type: string
responses:
'200':
description: Contains the requested array of messages
content:
application/json:
schema:
$ref: '#/components/schemas/MessageListRetrievalResponse'
'400':
$ref: '#/components/responses/bad-request'
x-code-samples:
- lang: C#
source: |
using System;
using System.IO;
using System.Net;
class MainClass
{
public static void Main(string[] args)
{
/**
Note in the query string
we have a filter to get only the
SENT messages
*/
string myURI = "https://api.bulksms.com/v1/messages?filter=type%3DSENT";
string myUsername = "username";
string myPassword = "yourPassword";
var request = WebRequest.Create(myURI);
request.Credentials = new NetworkCredential(myUsername, myPassword);
request.PreAuthenticate = true;
request.Method = "GET";
request.ContentType = "application/json";
try
{
// make the call to the API
var response = request.GetResponse();
// read the response and print it to the console
var reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
} catch (WebException ex) {
// show the general message
Console.WriteLine("An error occurred:" + ex.Message);
// print the detail that come with the HTTP error
var reader = new StreamReader(ex.Response.GetResponseStream());
Console.WriteLine("Error details:" + reader.ReadToEnd());
}
}
}
post:
tags:
- Message
summary: Send Messages
operationId: Message_sendBatchMessages
description: >
Send messages to one or more recipients.
You can post up to `30 000` messages in a batch.
But note that the `deduplication-id` is set per submission, so it is
recommended that you use a smaller number, like `4000` per submission in
order to make resubmissions on network failures more practical.
#### Repliability
When a sent message is _repliable_, the BulkSMS system can process an
SMS response sent by your recipient.
The message sent by your customer is called a mobile originating (MO)
message and would be available under `RECEIVED` messages.
You can obtain a list of MOs using the [retrieve messages API
call](https://www.bulksms.com/developer/json/v1/#).
In addition you can also get a list of the MOs that are associated with
a specific sent message (see the [list related messages API
call](https://www.bulksms.com/developer/json/v1/#)).
If you use a specific _sender id_ in the `from` property of the send
message, the message will not be repliable.
If you want a message to be repliable, you need to specify `REPLIABLE`
in the `from.type` property.
If you do not set the `from` property, your account settings are
considered to determine whether or not the message is repliable.
If the _default repliable_ setting on your account is _yes_ then the
message will be repliable.
If this setting is _no_, the message will not be repliable.
#### Body templates
When sending a message you can use template fields to customise the
message text.
*Field based templates* allow you to create a message with place-holders
for custom fields. Fields are identified by a zero based index; the
first field is `F0`, the second is `F1` and so on.
For example, let's say you want to send a daily SMS message to all your
clients that tell them what their current balance is. The `body` of the
message could look something like this
```
Good morning {F0######}, your balance is {F1######}
```
In this message, the first field, `F0`, is the name of the customer and
he second field `F1` is the balance for that customer. The `#` used to
specify the maximum length of the field. Note that the maximum length
allowed for the value includes the space taken by the braces, template
name and hash symbol. For example, the value `{F0#}` specifies a
maximum length of `5`. If the data is longer than this length, the data
will be truncated when the message body is constructed.
The data fields are provided in the property named `fields` in the `to`
element. Here is a complete example of how this might look
```
{
"body": "Good morning {F0######}, your balance is {F1######}",
"to": [
{"address": "27456789","fields": ["Harry", "$1345.23"] },
{"address": "27456785","fields": ["Sally", "$2345.58"] }
]
}
```
If you are sending to contacts (or to groups) in your phonebook, you can
use the *Phonebook based templates*. These are similar to the templates
described above, but they have specific names. The template for the
contact's first name is identified by `fn` and the template for the
contact's surname is identified by `sn`. Below in an example that will
work if the numbers are registered in your phonebook.
```
{
"body": "Hi {fn######} {sn######}, have a great day!",
"to": [
{"address": "27456789" },
{"address": "27456785" }
]
}
```
parameters:
- description: >
Safeguards against the possibility of sending the same messages more
than once.
If a communication failure occurs during a submission, you cannot be
sure that the submission was processed; therefore you would have to
submit it again. When you post the retry, you must use the
`deduplication-id` of the original post. The BulkSMS system uses
this ID to check that the request was not previously processed. (If
it was previously processed, the submission will succeed, and the
behaviour will be indistinguishable to you from a non-duplicated
submission). The ID expires after about 12 hours.
in: query
name: deduplication-id
schema:
format: int32
type: integer
- description: >
Specifies how to deal with message text that contains characters not
present in the GSM 03.38 character set.
Messages that contain only GSM 03.38 characters are not affected by
this setting.
If the value is `true` then a message containing non-GSM 03.38
characters will be transmitted as a Unicode SMS (which is most
likely more costly).
Please note: when `auto-unicode` is `true` and the value of the
`encoding` property is specified as `UNICODE`, the message will
always be sent as `UNICODE`.
If the value is `false` and the `encoding` property is `TEXT` then
non-GSM 03.38 characters will be replaced by the `?` character.
When using this setting on the API, you should take case to ensure
that your message is _clean_.
Invisible unicode and unexpected characters could unintentionally
convert an message to `UNICODE`. A common mistake is to use the
backtick character (\`) which is unicode and will turn your `TEXT`
message into a `UNICODE` message.
in: query
name: auto-unicode
schema:
default: false
type: boolean
- description: >
Allows you to send a message in the future.
An example value is `2019-02-18T13:00:00+02:00`. It encodes to
`2019-02-18T13%3A00%3A00%2B02%3A00`.
Credits are deducted from your account immediately. Once submitted,
scheduled messages cannot be changed or cancelled.
The date can be a maximum of two years in the future. If the value
is in the past, the message will be sent immediately.
The date format requires you to supply an offset from UTC. You can
decide to use the offset of your timezone, or maybe the zone of the
recipient's location is more appropriate.
If the destination is a group, the group members are determined at
the time that you submit the message; not the time the message is
scheduled to be sent.
in: query
name: schedule-date
schema:
format: date-time
type: string
- description: >
A note that is stored together with a scheduled submission, which
could be used to more easily identify the scheduled submission at a
later date.
The value of this field is ignored if the `schedule-date` is not
provided.
A value that is longer than 256 characters is truncated.
in: query
name: schedule-description
schema:
type: string
requestBody:
description: >
Contains details of the message (or messages) that you want to send.
One `SubmissionEntry` can produce many messages, and your request may
contain multiple such entries.
content:
application/json:
schema:
$ref: '#/components/schemas/MessageSendBatchMessagesRequest'
required: true
responses:
'201':
description: An array of the messages that were created from the request
content:
application/json:
schema:
$ref: '#/components/schemas/MessageSendBatchMessagesResponse'
'400':
$ref: '#/components/responses/bad-request'
'403':
$ref: '#/components/responses/credits'
x-code-samples:
- lang: PHP
source: >
<?
// Your PHP installation needs cUrl support, which not all PHP
installations
// include by default.
// To run under docker:
// docker run -v $PWD:/code php:7.3.2-alpine php
/code/code_sample.php
$username = 'your_username';
$password = 'your_password';
$messages = array(
array('to'=>'+1233454567', 'body'=>'Hello World!'),
array('to'=>'+1233454568', 'body'=>'Hello World!')
);
$result = send_message( json_encode($messages),
'https://api.bulksms.com/v1/messages?auto-unicode=true&longMessageMaxParts=30',
$username, $password );
if ($result['http_status'] != 201) {
print "Error sending: " . ($result['error'] ? $result['error'] : "HTTP status ".$result['http_status']."; Response was " .$result['server_response']);
} else {
print "Response " . $result['server_response'];
// Use json_decode($result['server_response']) to work with the response further
}
function send_message ( $post_body, $url, $username, $password) {
$ch = curl_init( );
$headers = array(
'Content-Type:application/json',
'Authorization:Basic '. base64_encode("$username:$password")
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_body );
// Allow cUrl functions 20 seconds to execute
curl_setopt ( $ch, CURLOPT_TIMEOUT, 20 );
// Wait 10 seconds while trying to connect
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
$output = array();
$output['server_response'] = curl_exec( $ch );
$curl_info = curl_getinfo( $ch );
$output['http_status'] = $curl_info[ 'http_code' ];
$output['error'] = curl_error($ch);
curl_close( $ch );
return $output;
}
?>
- lang: C#
source: |
using System;
using System.IO;
using System.Net;
using System.Text;
class MainClass
{
public static void Main(string[] args)
{
// This URL is used for sending messages
string myURI = "https://api.bulksms.com/v1/messages";
// change these values to match your own account
string myUsername = "username";
string myPassword = "password";
// the details of the message we want to send
string myData = "{to: \"1111111\", body:\"Hello Mr. Smith!\"}";
// build the request based on the supplied settings
var request = WebRequest.Create(myURI);
// supply the credentials
request.Credentials = new NetworkCredential(myUsername, myPassword);
request.PreAuthenticate = true;
// we want to use HTTP POST
request.Method = "POST";
// for this API, the type must always be JSON
request.ContentType = "application/json";
// Here we use Unicode encoding, but ASCIIEncoding would also work
var encoding = new UnicodeEncoding();
var encodedData = encoding.GetBytes(myData);
// Write the data to the request stream
var stream = request.GetRequestStream();
stream.Write(encodedData, 0, encodedData.Length);
stream.Close();
// try ... catch to handle errors nicely
try
{
// make the call to the API
var response = request.GetResponse();
// read the response and print it to the console
var reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
}
catch (WebException ex)
{
// show the general message
Console.WriteLine("An error occurred:" + ex.Message);
// print the detail that comes with the error
var reader = new StreamReader(ex.Response.GetResponseStream());
Console.WriteLine("Error details:" + reader.ReadToEnd());
}
}
}
- lang: Java
source: |
import java.net.*;
import java.util.Base64;
import java.io.*;
public class MainClass {
static public void main(String[] args) throws Exception {
// This URL is used for sending messages
String myURI = "https://api.bulksms.com/v1/messages";
// change these values to match your own account
String myUsername = "username";
String myPassword = "password";
// the details of the message we want to send
String myData = "{to: \"1111111\", encoding: \"UNICODE\", body: \"Dobrá práce! Jak se máš?\"}";
// if your message does not contain unicode, the "encoding" is not required:
// String myData = "{to: \"1111111\", body: \"Hello Mr. Smith!\"}";
// build the request based on the supplied settings
URL url = new URL(myURI);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.setDoOutput(true);
// supply the credentials
String authStr = myUsername + ":" + myPassword;
String authEncoded = Base64.getEncoder().encodeToString(authStr.getBytes());
request.setRequestProperty("Authorization", "Basic " + authEncoded);
// we want to use HTTP POST
request.setRequestMethod("POST");
request.setRequestProperty( "Content-Type", "application/json");
// write the data to the request
OutputStreamWriter out = new OutputStreamWriter(request.getOutputStream());
out.write(myData);
out.close();
// try ... catch to handle errors nicely
try {
// make the call to the API
InputStream response = request.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(response));
String replyText;
while ((replyText = in.readLine()) != null) {
System.out.println(replyText);
}
in.close();
} catch (IOException ex) {
System.out.println("An error occurred:" + ex.getMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(request.getErrorStream()));
// print the detail that comes with the error
String replyText;
while ((replyText = in.readLine()) != null) {
System.out.println(replyText);
}
in.close();
}
request.disconnect();
}
}
- lang: Node.js
source: |
const https = require('https');
let username = 'your_username';
let password = 'your_password';
let postData = JSON.stringify({
'to' : ['+111111123', '+111111124'],
'body': 'Hello World!'
});
let options = {
hostname: 'api.bulksms.com',
port: 443,
path: '/v1/messages',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length,
'Authorization': 'Basic ' + Buffer.from(username + ':' + password).toString('base64')
}
};
let req = https.request(options, (resp) => {
console.log('statusCode:', resp.statusCode);
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log("Response:", data);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
/messages/send:
get:
tags:
- Message
summary: Send message by simple GET or POST
operationId: Message_submitMessage
description: >
A really simple interface for people who require a GET mechanism to
submit a single message.