-
Notifications
You must be signed in to change notification settings - Fork 8
Basics
First things first.
Let's say you want to call the posts
method on this web api.
It looks lite it returns a list of posts
. So you need to define a class that looks like a post
.
public class Post
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
You'll also need an interface describing the api you're going to call.
public interface ITypicodeApi
{
[Get("posts")]
Task<List<Post>> GetPosts();
}
Internet is asynchronous. That is why you return a Task
of List<Post>
.
Now. This interface is used by WebAnchor to generate a HTTP Request. How?
Like this.
// Create the api. Supply host protocol and domain to tell Web Anchor where this api is located.
var api = Api.For<ITypicodeApi>("http://jsonplaceholder.typicode.com");
// And call it
var posts = await api.GetPosts();
// -> HTTP GET http://jsonplaceholder.typicode.com/posts
That's nice and all, but how then, would you ask the api for a single post
, given it's id
?
Well, you could use the possibility to substitute parts of your url, with the value of a parameter.
Add another method signature to your ITypicodeApi
interface.
[Get("posts/{id}")]
Task<Post> GetPost(int id);
See the part of the GetAttribute
parameter that says {id}
? It will be replaced with the value of a method parameter with a matching name. How great? Very great.
var post = await api.GetPost(5);
// -> HTTP GET http://jsonplaceholder.typicode.com/post/5
Cool. Method parameters can also be used to generate query string parameters. Take a look at how you can modify the GetPosts
signature you created earlier.
[Get("posts")]
Task<List<Post>> GetPosts(int? userId = null);
var posts = await api.GetPosts(2);
// -> HTTP GET http://jsonplaceholder.typicode.com/posts?userId=2
Any method parameter that cannot be found as a part of the url enclosed with {}
, is translated to a query string parameter.
Now, you see how posts
begin both of our 2 methods so far. This can be moved "up" to Api-level, like this.
[BaseLocation("posts")]
public interface ITypicodeApi
{
[Get("")]
Task<List<Post>> GetPosts();
[Get("{id}")]
Task<Post> GetPost(int id);
}
So this would cover the very basics that you need to get started. However, you'll soon realize that there are lots of situations where you will need more granular control. Lucky for you, WebAnchor is designed to be very extensible, and you can easily get to the very core of the http-related stuff for inspection or modification. We'll talk about some built-in stuff in the next section.
- Getting started
- Basics (Http GET & Base Location)
- Basics pt. 2 (POST/PUT/DELETE, HttpResponseMessage, Exceptions, HttpClient, IDisposable)
- Building an HttpRequestMessage
- Parameter attributes
- Handling responses
- ApiSettings
- Typical setup (Develop/Test/Production & Mocking)
- Logging
- Testing
- Generic Api
- Multipart