Skip to content

Commit 65d9ad8

Browse files
committed
Moving other bits
1 parent adc0ce4 commit 65d9ad8

File tree

10 files changed

+291
-290
lines changed

10 files changed

+291
-290
lines changed

docs/docs/usage/basics.md

-145
Original file line numberDiff line numberDiff line change
@@ -21,148 +21,3 @@ Essentially, RestSharp is a wrapper around `HttpClient` that allows you to do th
2121
The best way to call an external HTTP API is to create a typed client, which encapsulates RestSharp calls and doesn't expose the `RestClient` instance in public.
2222

2323
You can find an example of a Twitter API client on the [Example](example.md) page.
24-
25-
26-
## Handling responses
27-
28-
All `Execute{Method}Async` functions return an instance of `RestResponse`. Similarly, `Execute{Method}Async<T>` return a generic instance of `RestResponse<T>` where `T` is the response object type.
29-
30-
Response object contains the following properties:
31-
32-
| Property | Type | Description |
33-
|--------------------------|-----------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
34-
| `Request` | `RestRequest` | Request instance that was used to get the response. |
35-
| `ContentType` | `string?` | Response content type. `Null` if response has no content. |
36-
| `ContentLength` | `long?` | Response content length. `Null` if response has no content. |
37-
| `ContentEncoding` | `ICollection<string>` | Content encoding collection. Empty if response has no content. |
38-
| `Content` | `string?` | Response content as string. `Null` if response has no content. |
39-
| `IsSuccessfulStatusCode` | `bool` | Indicates if response was successful, so no errors were reported by the server. Note that `404` response code means success. |
40-
| `ResponseStatus` | `None`, `Completed`, `Error`, `TimedOut`, `Aborted` | Response completion status. Note that completed responses might still return errors. |
41-
| `IsSuccessful` | `bool` | `True` when `IsSuccessfulStatusCode` is `true` and `ResponseStatus` is `Completed`. |
42-
| `StatusDescription` | `string?` | Response status description, if available. |
43-
| `RawBytes` | `byte[]?` | Response content as byte array. `Null` if response has no content. |
44-
| `ResponseUri` | `Uri?` | URI of the response, which might be different from request URI in case of redirects. |
45-
| `Server` | `string?` | Server header value of the response. |
46-
| `Cookies` | `CookieCollection?` | Collection of cookies received with the response, if any. |
47-
| `Headers` | Collection of `HeaderParameter` | Response headers. |
48-
| `ContentHeaders` | Collection of `HeaderParameter` | Response content headers. |
49-
| `ErrorMessage` | `string?` | Transport or another non-HTTP error generated while attempting request. |
50-
| `ErrorException` | `Exception?` | Exception thrown when executing the request, if any. |
51-
| `Version` | `Version?` | HTTP protocol version of the request. |
52-
| `RootElement` | `string?` | Root element of the serialized response content, only works if deserializer supports it. |
53-
54-
In addition, `RestResponse<T>` has one additional property:
55-
56-
| Property | Type | Description |
57-
|----------|------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|
58-
| `Data` | `T?` | Deserialized response object. `Null` if there's no content in the response, deserializer failed to understand the response content, or if request failed. |
59-
60-
### JSON streaming APIs
61-
62-
For HTTP API endpoints that stream the response data (like [Twitter search stream](https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream)) you can use RestSharp with `StreamJsonAsync<T>`, which returns an `IAsyncEnumerable<T>`:
63-
64-
```csharp
65-
public async IAsyncEnumerable<SearchResponse> SearchStream(
66-
[EnumeratorCancellation] CancellationToken cancellationToken = default
67-
) {
68-
var response = _client.StreamJsonAsync<TwitterSingleObject<SearchResponse>>(
69-
"tweets/search/stream", cancellationToken
70-
);
71-
72-
await foreach (var item in response.WithCancellation(cancellationToken)) {
73-
yield return item.Data;
74-
}
75-
}
76-
```
77-
78-
The main limitation of this function is that it expects each JSON object to be returned as a single line. It is unable to parse the response by combining multiple lines into a JSON string.
79-
80-
### Uploading files
81-
82-
To add a file to the request you can use the `RestRequest` function called `AddFile`. The main function accepts the `FileParameter` argument:
83-
84-
```csharp
85-
request.AddFile(fileParameter);
86-
```
87-
88-
You can instantiate the file parameter using `FileParameter.Create` that accepts a bytes array, or `FileParameter.FromFile`, which will load the file from disk.
89-
90-
There are also extension functions that wrap the creation of `FileParameter` inside:
91-
92-
```csharp
93-
// Adds a file from disk
94-
AddFile(parameterName, filePath, contentType);
95-
96-
// Adds an array of bytes
97-
AddFile(parameterName, bytes, fileName, contentType);
98-
99-
// Adds a stream returned by the getFile function
100-
AddFile(parameterName, getFile, fileName, contentType);
101-
```
102-
103-
Remember that `AddFile` will set all the necessary headers, so please don't try to set content headers manually.
104-
105-
You can also provide file upload options to the `AddFile` call. The options are:
106-
- `DisableFilenameEncoding` (default `false`): if set to `true`, RestSharp will not encode the file name in the `Content-Disposition` header
107-
- `DisableFilenameStar` (default `true`): if set to `true`, RestSharp will not add the `filename*` parameter to the `Content-Disposition` header
108-
109-
Example of using the options:
110-
111-
```csharp
112-
var options = new FileParameterOptions {
113-
DisableFilenameEncoding = true,
114-
DisableFilenameStar = false
115-
};
116-
request.AddFile("file", filePath, options: options);
117-
```
118-
119-
The options specified in the snippet above usually help when you upload files with non-ASCII characters in their names.
120-
121-
### Downloading binary data
122-
123-
There are two functions that allow you to download binary data from the remote API.
124-
125-
First, there's `DownloadDataAsync`, which returns `Task<byte[]`. It will read the binary response to the end, and return the whole binary content as a byte array. It works well for downloading smaller files.
126-
127-
For larger responses, you can use `DownloadStreamAsync` that returns `Task<Stream>`. This function allows you to open a stream reader and asynchronously stream large responses to memory or disk.
128-
129-
## Blazor support
130-
131-
Inside a Blazor webassembly app, you can make requests to external API endpoints. Microsoft examples show how to do it with `HttpClient`, and it's also possible to use RestSharp for the same purpose.
132-
133-
You need to remember that webassembly has some platform-specific limitations. Therefore, you won't be able to instantiate `RestClient` using all of its constructors. In fact, you can only use `RestClient` constructors that accept `HttpClient` or `HttpMessageHandler` as an argument. If you use the default parameterless constructor, it will call the option-based constructor with default options. The options-based constructor will attempt to create an `HttpMessageHandler` instance using the options provided, and it will fail with Blazor, as some of those options throw thw "Unsupported platform" exception.
134-
135-
Here is an example how to register the `RestClient` instance globally as a singleton:
136-
137-
```csharp
138-
builder.Services.AddSingleton(new RestClient(new HttpClient()));
139-
```
140-
141-
Then, on a page you can inject the instance:
142-
143-
```html
144-
@page "/fetchdata"
145-
@using RestSharp
146-
@inject RestClient _restClient
147-
```
148-
149-
And then use it:
150-
151-
```csharp
152-
@code {
153-
private WeatherForecast[]? forecasts;
154-
155-
protected override async Task OnInitializedAsync() {
156-
forecasts = await _restClient.GetJsonAsync<WeatherForecast[]>("http://localhost:5104/weather");
157-
}
158-
159-
public class WeatherForecast {
160-
public DateTime Date { get; set; }
161-
public int TemperatureC { get; set; }
162-
public string? Summary { get; set; }
163-
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
164-
}
165-
}
166-
```
167-
168-
In this case, the call will be made to a WebAPI server hosted at `http://localhost:5104/weather`. Remember that if the WebAPI server is not hosting the webassembly itself, it needs to have a CORS policy configured to allow the webassembly origin to access the API endpoint from the browser.

docs/docs/usage/client.md

+40
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,43 @@ One way of doing it is to use `RestClient` constructors that accept an instance
7272

7373
Another option is to use a simple HTTP client factory as described [above](#simple-factory).
7474

75+
## Blazor support
76+
77+
Inside a Blazor webassembly app, you can make requests to external API endpoints. Microsoft examples show how to do it with `HttpClient`, and it's also possible to use RestSharp for the same purpose.
78+
79+
You need to remember that webassembly has some platform-specific limitations. Therefore, you won't be able to instantiate `RestClient` using all of its constructors. In fact, you can only use `RestClient` constructors that accept `HttpClient` or `HttpMessageHandler` as an argument. If you use the default parameterless constructor, it will call the option-based constructor with default options. The options-based constructor will attempt to create an `HttpMessageHandler` instance using the options provided, and it will fail with Blazor, as some of those options throw thw "Unsupported platform" exception.
80+
81+
Here is an example how to register the `RestClient` instance globally as a singleton:
82+
83+
```csharp
84+
builder.Services.AddSingleton(new RestClient(new HttpClient()));
85+
```
86+
87+
Then, on a page you can inject the instance:
88+
89+
```html
90+
@page "/fetchdata"
91+
@using RestSharp
92+
@inject RestClient _restClient
93+
```
94+
95+
And then use it:
96+
97+
```csharp
98+
@code {
99+
private WeatherForecast[]? forecasts;
100+
101+
protected override async Task OnInitializedAsync() {
102+
forecasts = await _restClient.GetJsonAsync<WeatherForecast[]>("http://localhost:5104/weather");
103+
}
104+
105+
public class WeatherForecast {
106+
public DateTime Date { get; set; }
107+
public int TemperatureC { get; set; }
108+
public string? Summary { get; set; }
109+
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
110+
}
111+
}
112+
```
113+
114+
In this case, the call will be made to a WebAPI server hosted at `http://localhost:5104/weather`. Remember that if the WebAPI server is not hosting the webassembly itself, it needs to have a CORS policy configured to allow the webassembly origin to access the API endpoint from the browser.

docs/docs/usage/execute.md

+29
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,32 @@ var statusCode = client.PostJsonAsync("orders", request, cancellationToken);
141141
```
142142

143143
The same two extensions also exist for `PUT` requests (`PutJsonAsync`);
144+
145+
## Downloading binary data
146+
147+
There are two functions that allow you to download binary data from the remote API.
148+
149+
First, there's `DownloadDataAsync`, which returns `Task<byte[]`. It will read the binary response to the end, and return the whole binary content as a byte array. It works well for downloading smaller files.
150+
151+
For larger responses, you can use `DownloadStreamAsync` that returns `Task<Stream>`. This function allows you to open a stream reader and asynchronously stream large responses to memory or disk.
152+
153+
## JSON streaming
154+
155+
For HTTP API endpoints that stream the response data (like [Twitter search stream](https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream)) you can use RestSharp with `StreamJsonAsync<T>`, which returns an `IAsyncEnumerable<T>`:
156+
157+
```csharp
158+
public async IAsyncEnumerable<SearchResponse> SearchStream(
159+
[EnumeratorCancellation] CancellationToken cancellationToken = default
160+
) {
161+
var response = _client.StreamJsonAsync<TwitterSingleObject<SearchResponse>>(
162+
"tweets/search/stream", cancellationToken
163+
);
164+
165+
await foreach (var item in response.WithCancellation(cancellationToken)) {
166+
yield return item.Data;
167+
}
168+
}
169+
```
170+
171+
The main limitation of this function is that it expects each JSON object to be returned as a single line. It is unable to parse the response by combining multiple lines into a JSON string.
172+

docs/docs/usage/request.md

+40
Original file line numberDiff line numberDiff line change
@@ -289,3 +289,43 @@ When you call `AddXmlBody`, it does the following for you:
289289
Do not send XML string to `AddXmlBody`; it won't work!
290290
:::
291291

292+
## Uploading files
293+
294+
To add a file to the request you can use the `RestRequest` function called `AddFile`. The main function accepts the `FileParameter` argument:
295+
296+
```csharp
297+
request.AddFile(fileParameter);
298+
```
299+
300+
You can instantiate the file parameter using `FileParameter.Create` that accepts a bytes array, or `FileParameter.FromFile`, which will load the file from disk.
301+
302+
There are also extension functions that wrap the creation of `FileParameter` inside:
303+
304+
```csharp
305+
// Adds a file from disk
306+
AddFile(parameterName, filePath, contentType);
307+
308+
// Adds an array of bytes
309+
AddFile(parameterName, bytes, fileName, contentType);
310+
311+
// Adds a stream returned by the getFile function
312+
AddFile(parameterName, getFile, fileName, contentType);
313+
```
314+
315+
Remember that `AddFile` will set all the necessary headers, so please don't try to set content headers manually.
316+
317+
You can also provide file upload options to the `AddFile` call. The options are:
318+
- `DisableFilenameEncoding` (default `false`): if set to `true`, RestSharp will not encode the file name in the `Content-Disposition` header
319+
- `DisableFilenameStar` (default `true`): if set to `true`, RestSharp will not add the `filename*` parameter to the `Content-Disposition` header
320+
321+
Example of using the options:
322+
323+
```csharp
324+
var options = new FileParameterOptions {
325+
DisableFilenameEncoding = true,
326+
DisableFilenameStar = false
327+
};
328+
request.AddFile("file", filePath, options: options);
329+
```
330+
331+
The options specified in the snippet above usually help when you upload files with non-ASCII characters in their names.

0 commit comments

Comments
 (0)